Arumai
Arumai

Reputation: 75

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?

Upvotes: 3

Views: 1772

Answers (4)

Shaunak D
Shaunak D

Reputation: 20646

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

Upvotes: 2

Dhaval
Dhaval

Reputation: 2861

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

Upvotes: 1

anubhava
anubhava

Reputation: 786011

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]

Upvotes: 2

Ionic
Ionic

Reputation: 3935

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

Upvotes: 2

Related Questions