finding specific character from substring

78 views Asked by At

I have this function to find string for the first time:

var strng:String = new String(txtSource.text)
var position:Number = new Number();
position = strng.indexOf("<img pg",0);          
strng = strng.substring(position + 4);
position = strng.indexOf(">");
strng = strng.substring(0, position);
textcontrol1.text = String(strng);

Now I get below string as answer

<img pg="asStoryVid" class="" vspace="0" marginheight="0" marginwidth="0" width="300" border="0" src="http://www.abc.com/thumb/msid-22087805,width-300,resizemode-4/xyz.jpg" 
alt="" title="" ag="">

Now, further I want only src="http://www.abc.com/thumb/msid-22087805,width-300,resizemode-4/xyz.jpg" from above string. For that I have write this function

var strng1:String = new String(textcontrol1.text)
var position1:Number = new Number();
position1 = strng1.indexOf('src="http://',0);                   
strng1 = strng1.substring(position1 + 0);
position1 = strng1.indexOf('"');
strng1 = strng1.substring(0, position1);
textcontrol1.text = String(strng1);

But in output I getting a no string Any one can show me where I m wrong?

2

There are 2 answers

0
Alexander Farber On

No no no - just use a regex:

var str:String = '<img pg="asStoryVid" class="" vspace="0" marginheight="0" marginwidth="0" width="300" border="0" src="http://www.abc.com/thumb/msid-22087805,width-300,resizemode-4/xyz.jpg" alt="" title="" ag="">';
//var str:String = new String(textcontrol1.text);
var pattern:RegExp = /<img [^>]*src="([^"]+)"/i; 
var result:Object = pattern.exec(str);

if (result) {
    //textcontrol1.text = result[1];
    trace(result[1]);
}

The [^>]* means: zero or more characters, but not closing bracket >

The [^"]+ means: one or more characters, but not a quote

And the round brackets capture it into result[1]

And as a general advice: keep your regexes simple by not putting stuff into them that you don't need to capture (i.e. do not add class= or width= to your regex).

0
Yasuyuki  Uno On

Try this code.

var strng1:String = new String(textcontrol1.text);
var position1:Number = new Number();
position1 = strng1.indexOf('src="http://',0);
strng1 = strng1.substring(position1 + 0);
// search 2nd " character
position1 = strng1.indexOf('"', strng1.indexOf('"') + 1);

strng1 = strng1.substring(0, position1 + 1);

textcontrol1.text = String(strng1);