JavaScript - Replace specific word index in html string - Stack Overflow

I have a challenging mission in JS string manipulation:There is a HTML string in which I need to repla

I have a challenging mission in JS string manipulation: There is a HTML string in which I need to replace a word at a specific word index. The word index is the number of the word when ignoring the HTML tags.

For example, here is the HTML string:

<span style="font-family:Times New Roman;">At times like this I don't know what to
do. Other times I have no problem.</span>

The task is to replace word number 2 in the html (which is the word times) with the text: <span style="color:red;">times</span>

So the final HTML string should be:

<span style="font-family:Times New Roman;">At <span style="color:red;">times</span> 
like this I don't know what to do. Other times I have no problem.</span>

Any ideas for this challenge?

I have a challenging mission in JS string manipulation: There is a HTML string in which I need to replace a word at a specific word index. The word index is the number of the word when ignoring the HTML tags.

For example, here is the HTML string:

<span style="font-family:Times New Roman;">At times like this I don't know what to
do. Other times I have no problem.</span>

The task is to replace word number 2 in the html (which is the word times) with the text: <span style="color:red;">times</span>

So the final HTML string should be:

<span style="font-family:Times New Roman;">At <span style="color:red;">times</span> 
like this I don't know what to do. Other times I have no problem.</span>

Any ideas for this challenge?

Share Improve this question asked Sep 3, 2013 at 10:57 LightLight 1,6873 gold badges23 silver badges39 bronze badges 1
  • Do you want to replace all occurrences of that word or just the first one ? – Denys Séguret Commented Sep 3, 2013 at 11:21
Add a ment  | 

5 Answers 5

Reset to default 2

I would first find the word by tokenizing the filtered HTML, and then do the replacement.

Let's start from your string :

var html = '<span style="font-family:Times New Roman;">At times like this don\'t know what to do. Other times I have no problem.</span>';

Case 1, you want to replace all occurrences :

var tokens = html.replace(/<[^>]*>/g,'').split(/\W+/).filter(Boolean);
var newHTML = html.replace(new RegExp('\\b'+tokens[1]+'\\b', 'g'), function(s){
     return '<span style="color:red;">'+s+'</span>'
});

Demonstration

Case 2, you just want to replace the word at the specified index (this one is surprisingly tricky) :

var tokens = html.replace(/<[^>]*>/g,'').split(/\W+/).filter(Boolean);
var wordToReplaceIndex = 1, wordToReplace = tokens[wordToReplaceIndex];
var occIndex = 0;
for (var i=0; i<wordToReplaceIndex; i++) {
   if (tokens[i]===wordToReplace) occIndex++;
}
i=0;
var newHTML = html.replace(new RegExp('\\b'+wordToReplace+'\\b', 'g'), function(s){
    return (i++===occIndex) ? '<span style="color:red;">'+s+'</span>' : s
});

Demonstration

Alternate solution for case 2 :

var i=0, wordToReplaceIndex = 1;
var newHTML = html.replace(/>([^<]+)</, function(txt) {
  return txt.replace(/\w+/g, function(s) {
    return i++==wordToReplaceIndex ? '<span style="color:red;">'+s+'</span>' : s;
  })
});

Can you spot why the second one was tricky ? ;)

I think a decent solution would be to split and replace then join. Here's an example:

<div id="replace-me">Hello, world</div>

replaceWordAtIndex = function (text, index, replacement) { 
    text = text.split(' ');
    text[index] = replacement;
    text = text.join(' ');
    return text;
}

wrapWordAtIndex = function (text, index, before, after) { 
    text = text.split(' ');
    text[index] = before + text[index] + after;
    text = text.join(' ');
    return text;
}

var obj = document.getElementById('replace-me');
obj.innerText = replaceWordAtIndex(obj.innerText, 1, 'Universe');
obj.innerHTML = wrapWordAtIndex(obj.innerText, 1, '<b>', '</b>');

Should result in:

<div id="replace-me">Hello, <b>Universe</b></div>

And here's a JSFiddle for you to see it in action

function smartReplace(str,index,strReplace){

    var wStart=0,wEnd=0;
    var startInd=str.indexOf(">")+1;    
    var wc=0;
    for(i=startInd;i<str.length;i++)
    {
        if (str.charAt(i) == ' ')
        {
            wc=wc+1;
            if (wc==index) 
            {   
                wEnd=i-1;
                break;
            }
            wStart=i+1;
        }
    }

    var newString = str.substring(0,wStart) + strReplace + str.substring((wEnd +1),(str.length-1));
    document.write(newString);
}

> call the smartReplace() like follows

var str1="<span style=\"font-family:Times New Roman;\">At times like this I don't know what to do. Other times I have no problem.</span>)";
smartReplace(str1,3,"<span style=\"color:red;\">times</span>");
var html = '<span style="font-family:Times New Roman;">At times like this don\'t know what to do. Other times I have no problem.</span>';
var tokens = html.replace("Times","<span style="color:red;">times</span>");

ive been using this jQuery plugin to replace/edit text in any part of the DOM. quite helpful and easy to use with plete REGEX support

http://benalman./projects/jquery-replacetext-plugin/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745344937a4623500.html

相关推荐

  • JavaScript - Replace specific word index in html string - Stack Overflow

    I have a challenging mission in JS string manipulation:There is a HTML string in which I need to repla

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信