4

I have a data.text string that returns a value like:

<span>Name</span>Message

Is it possible in Javascript to take this value and split in to two so that I can get 'Name' and 'Message' in two different variables?

I tried,

var str = data.text;

var arr[] = str.split("</span>", 2);

var str1 = arr[0];
var theRest = arr[1];

But didn't work

Tushar
  • 85,780
  • 21
  • 159
  • 179
Hashan Wijetunga
  • 181
  • 2
  • 3
  • 9

3 Answers3

1

There might be many methods but adding on using split.

var str = '<span>Name</span>Message';

var result = str.split(/<\/?span>/); // Split by span tags(opening and closing)
result.shift(); // Remove first empty element
console.log(result);
document.write(result);

The regex here <\/?span> will match the <span> and </span> both as in the regex \/? has made / optional.


You can also use following regex with non-capturing group.

(?:</?span>)(\w+)

var str = '<span>Name</span>Message';

var regex = /(?:<\/?span>)(\w+)/g,
  result = [];

while (res = regex.exec(str)) {
  result.push(res[1]);
}

console.log(result);
document.write(result);
Tushar
  • 85,780
  • 21
  • 159
  • 179
1

You should use a DOM parser to parse HTML.

var str = "<span>Name</span>Message",
    el = document.createElement('div');
el.innerHTML = str;
[].map.call(el.childNodes, function(node) {
  return node.textContent;
}); // [ "Name", "Message" ]
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

You can replace the open label with a empty string and then split the string by the close label, something like this:

var values = data.text.replace('<span>', '').split('</span>');

console.log(values[0]); // Name
console.log(values[1]); // Message
lombervid
  • 136
  • 1
  • 3