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
  • 22,383
  • 32
  • 112
  • 130
Hari krishnan
  • 2,060
  • 4
  • 18
  • 27

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
  • 47,944
  • 19
  • 150
  • 166
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,185
  • 2
  • 24
  • 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
  • 1,041
  • 12
  • 26
  • 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
  • 142,382
  • 31
  • 172
  • 209