Wondering how to parse a string correctly using JavaScript? Take a look at the example below:
<strong>word</strong>: or <em>word</em> or <p><strong>word</strong>: this is a sentence</p> etc...
The objective is to convert each string into an array without the HTML elements present.
For instance:
<strong>word</strong>
This specific string should be converted to an array like this:
['word', ':']
Similarly, for the string:
<p><strong>word</strong>: this is a sentence</p>
The expected array output would be:
['word', ':', 'this', 'is', 'a', 'sentence']
If you are currently facing issues in achieving this outcome with your JavaScript code and it's generating individual characters instead of words, then have a look at the snippet provided below:
//w = the string I want to parse
var p = document.querySelector("p").innerText;
var result = p.split(' ').map(function(w) {
if (w === '')
return w;
else {
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = w;
const wordArr = Array.from(tempDivElement.textContent);
return wordArr;
}
});
console.log(result)
<p><strong>word</strong>: this is a sentence</p>