simplfy javascript code using regex
Posted
by
Pradyut Bhattacharya
on Stack Overflow
See other posts from Stack Overflow
or by Pradyut Bhattacharya
Published on 2010-12-29T21:45:37Z
Indexed on
2010/12/29
21:54 UTC
Read the original article
Hit count: 349
JavaScript
|regex
Hi I have a code which can show youtube videos if there are any links to youtube in the text
like for example the text
example at:- pradyut.dyndns.org
http://www.youtube.com/watch?v=-LiPMxFBLZY testing http://www.youtube.com/watch?v=Q3-l22b_Qg8&feature=related
this text i m forwarding to the function...
function to_youtubelink(text)
{
if ( text.indexOf ('<') > 0 || text.indexOf ('"') > 0 || text.indexOf ('>') > 0 )
return text;
else
{
var obj_text = new Array();
var oi = 0;
while(text.indexOf('http://') >=0)
{ //getting the paths
var si = text.indexOf('http://');
var gr = text.indexOf('\n', si);
var sp = text.indexOf(' ', si);
var ei;
if ( gr > 0 || sp > 0 )
{
if ( gr >0 && sp > 0 )
{
if ( gr < sp )
{
ei = gr ;
}
else
{
ei = sp ;
}
}
else if ( gr > 0)
{
ei = gr;
}
else
{
ei = sp;
}
}
else
{
ei = text.length;
}
var it = text.substring(si,ei);
if ( it.indexOf('"') > 0)
{
it.substring(0, it.indexOf('"') );
}
if(ei < 0)
ei = text.length;
else
ei = text.indexOf(' ', si) ;
obj_text[oi] = it;
text = text.replace( it, '[link_service]');
oi++;
}
var ob_text = new Array();
var ob =0;
for (oi=0; oi<obj_text.length; oi++)
{
if ( is_youtubelink( obj_text[oi] ) )
{
ob_text[ob] = to_utubelink(obj_text[oi]);
ob++;
}
}
oi = 0;
while ( text.indexOf('[link_service]') >=0 )
{
text = text.replace( '[link_service]', obj_text[oi]);
oi ++;
}
for (ob=0; ob<ob_text.length; ob++)
{
text = text +"\n\n" + ob_text[ob];
}
return text;
}
}
function is_youtubelink(text)
{
var matches = text.match(/http:\/\/(?:www\.)?youtube.*watch\?v=([a-zA-Z0-9\-_]+)/);
if (matches) {
return true;
} else {
return false;
}
}
function to_utubelink(text)
{
var video_id = text.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1)
{
video_id = video_id.substring(0, ampersandPosition);
}
text = "<iframe title=\"YouTube video player\" class=\"youtube-player\" type=\"text/html\" width=\"425\" height=\"350\" src=\"http://www.youtube.com/embed/" + video_id + "\" frameborder=\"0\"></iframe>"
return text;
}
now i m getting the output properly...
but i was thinking if the code could be done better and simplified using regex
...especially getting the urls part...
thanks
© Stack Overflow or respective owner