Thanks in advance. I am stuck with a problem. I have a string like this
var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";
I want to know the position of each occurrence of the span tag in the string. In the example string i have one span tag after 3rd word, one after 9th word , one after the 12th word. so the result array will be [3, 9, 12]. Please help me.
Edit : Also, can i be able to have the number of words inside each span tag in addition to the above array?
As you have tagged javascript/jQuery, one way would be to use .each() and split()
var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";
//Count position
var pos = [];
string.split(' ').forEach(function(val,i){
if(val.indexOf('<span>') > -1){
pos.push(i)
}
});
//Count words inside each `<span>`
var wordCount = $('<div/>').html(string).find('span').map(function(){
return this.innerText.split(' ').length
})
console.log(wordCount)
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With