Skip to content Skip to sidebar Skip to footer

Given Offsets, Adding Span To A Text String Using Javascript

I have string, call it s that contains some text, say var s = 'The cat in the hat'; I know that 'cat' starts at 4 and ends with 6. What is the best way to add the span so that I e

Solution 1:

You could use String#replace:

var s = 'The cat in the hat';
var keywords = ['cat', 'hat'];

for (var i=0; i < keywords.length; i++) {
    s = s.replace(keywords[i], '<span>$&</span>');
}

console.log(s); // The <span>cat</span> in the <span>hat</span>

Solution 2:

Try to replace like this...

var s = 'The cat in the hat'
s.replace(s.substring(4,7),'<span id="myid">' + s.substring(4,7) + '</span>');

OR

To replace both 'cat' and 'hat' use as follow:

var s = 'The cat in the hat';
var arr = ['cat', 'hat'];

for (var i=0; i < arr.length; i++) {
    s = s.replace(new RegExp(arr[i],"g"),'<span id="myid">' + arr[i] + '</span>');
}

Solution 3:

On there way is,

var s = 'The cat in the hat';
var newStr = '';
​var strArr = s.split(" ");
for (i=0;i<strArr.length;i++){
    alert(strArr[i]);
    if(strArr[i] == 'cat'){
        newStr  += ' <span>' + strArr[i] + '</span>';    
    }else{
            newStr  += ' ' + strArr[i];
    }       
}
alert(newStr);
​

Try this Fiddle


Post a Comment for "Given Offsets, Adding Span To A Text String Using Javascript"