find position of tag inside a string javascript

1.7k views Asked by At

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?

4

There are 4 answers

1
Shaunak D On BEST ANSWER

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

0
Ionic On

You can check the string using a regex like this:

var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";
var regex = /<span>/gi, result, indices = [];
while ((result = regex.exec(string))) {
     console.log(result.index);
}

This will print you every position of the tag <span>. You can adapt the While code and it should do the rest. :-)

2
Dhaval On

I think you are looking for this

var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";

var prevPos = 0;

var pos = [];
var words = [];
string.split(' ').forEach(function(val,i){
    if(val.indexOf('<span>') > -1){
        pos.push(i);
        var wordsCount = i - prevPos;
        prevPos = i; 
        words.push(wordsCount);

    }
});

console.log(pos);
console.log(words);
0
anubhava On

You can use:

var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";

var arr = string.split(/[\s>]+/);

var posn = [];
for(var p=-1; (p=arr.indexOf('<span', p+1)) >= 0; )
   posn.push(p)

//=> [3, 10, 14]