Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 233
Hashan Wijetunga Avatar asked Oct 29 '25 15:10

Hashan Wijetunga


2 Answers

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" ]
like image 75
Oriol Avatar answered Oct 31 '25 04:10

Oriol


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);
like image 38
Tushar Avatar answered Oct 31 '25 05:10

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!