I'm trying to split a string into an array of a lines but it isn't working, this is what I've tried so far -
value = '<p>line1</p><p>line2</p><p>line3</p>';
var lines = value.split('/<p>|<\/p>/');
console.log(lines.length);
//expecting 3 but output is 1
3 Answers 3
You are doing it wrong. Use it this way:
value = '<p>line1</p><p>line2</p><p>line3</p>';
var lines = value.split('</p><p>');
console.log(lines.length);
Also, to remove the first and last <p> and </p>, use the RegEx you have. And for those who ask that:
value = '<p>line1</p><p>line2</p><p>line3</p>';
value = value.replace(/^<p>|<\/p>$/g, "");
var lines = value.split('</p><p>');
console.log(lines.length);
console.log(lines);
Comments
A different approach could be to use native selectors (this implementation works with IE9+)
The idea is to hold your dom string in an actual html document body, and use querySelectorAll to fetch the paragraphs, transform the NodeList to an Array (the type returned by querySelectorAll). Then use the higher order function Array.prototype.map to build the array of lines you need.
This may seem overkill, but this is robust if some of your paragraphs happen to have extra attributes.
var sandbox = document.implementation.createHTMLDocument();
sandbox.body.innerHTML = '<p>line1</p><p>line2</p><p>line3</p>';
var paragraphs = Array.prototype.slice.call(sandbox.querySelectorAll('p'));
var lines = paragraphs.map(function (node) {
return node.innerText;
});
Comments
You can do that with a Regex.
value = '<p>line1</p><p>line2</p><p>line3</p>';
var v = value.replace(new RegExp("<p>(.*?)<\/p>", "g"), '1ドル\n');
var lines = v.split("\n");
lines.splice(-1);
console.log(lines);
https://jsfiddle.net/goe14nkf/
This returns your lines correctly: ["line1", "line2", "line3"]