0

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
asked Mar 15, 2016 at 11:24
0

3 Answers 3

1

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

answered Mar 15, 2016 at 11:27
Sign up to request clarification or add additional context in comments.

Comments

0

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;
});
answered Mar 15, 2016 at 11:41

Comments

0

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

answered Mar 15, 2016 at 11:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.