Hashan Wijetunga
Hashan Wijetunga

Reputation: 181

How to split a string by <span> tag in Javascript

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

Upvotes: 4

Views: 4548

Answers (3)

Tushar
Tushar

Reputation: 87203

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);

Upvotes: 1

Oriol
Oriol

Reputation: 288080

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" ]

Upvotes: 1

lombervid
lombervid

Reputation: 156

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

Upvotes: 0

Related Questions