1

I have a string that is returned from PHP through AJAX. The string value is like this:

<img src="/images/error.png"/>Invalid name`

Is there any way to cut the string starting with < and ending with > ?

I only need the <img/> from the string. I do not want to return the only <img/> from PHP because the full string is used in another page.

Lance Roberts
  • 21,757
  • 30
  • 108
  • 129
Hari krishnan
  • 1,920
  • 3
  • 17
  • 25

4 Answers4

3

What this what you meant? This alerts '<img src="/images/error.png"/>'

jsFiddle

var img = '<img src="/images/error.png"/>Invalid name';
var slice = img.slice(0, img.indexOf('>') + 1);
alert(slice);
Daniel Imms
  • 45,529
  • 17
  • 143
  • 160
1

You could use the split() method and add back in the last character.

var returnedString = '<img src="/images/error.png"/>Invalid name';
var returnedImage = returnedString.split('>')[0] +'>';
Paul Sham
  • 3,145
  • 2
  • 23
  • 31
1
var str = '<img src="/images/error.png"/>Invalid name';
alert(str.substring(str.indexOf('<'), str.indexOf('>')+1));

Edit: If this action is going to be repeated many times, then performance should also be considered. See 2 versions for each pure JS answer you got so far: the first 3 assume the tag starts at 0 ('<'), the last 3 don't: http://jsperf.com/15512887

I'm now proud of myself even if my answer won't be the chosen one :-)

targumon
  • 881
  • 10
  • 25
  • 1
    +1 `slice` vs `substring` is probably a little in `substring`'s favour as it's designed just for strings, where as `slice` works with all arrays. Split is much slower because it splits the array into two where we only actually care about the first one. – Daniel Imms Mar 20 '13 at 00:51
0

If you explicitly what to get the initial tag only of a string, then:

var s = '  <img src="/images/error.png"/>Invalid name';

var tag = '<' + s.split(/\W+/g)[1] + '>';

Though for robustness you should do something like:

var parts = s.split(/\W+/g);
var tag = parts.length? '<' + parts[1] + '>' : ''; 
RobG
  • 134,457
  • 30
  • 163
  • 204