简体   繁体   中英

find position of tag inside a string javascript

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?

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. :-)

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

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM