简体   繁体   中英

how to replace multiple words using javascript replace() function?

here is my code:

        var keys = keyword.split(' ');
        //alert(keys);
        for(var i=0; i<keys.length; i++)
            {
            var re = new RegExp(keys[i], "gi");
            var NewString = oldvar.replace(re, '<span style="background-color:#FFFF00">'+keys[i]+'</span>');
            document.getElementById("wordlist").innerHTML=NewString;
            alert(keys[i]);
            }

but here if I put a string "ab"; its split into two letters "a" and "b" and this replace function replace "a" but when it get "b" it overwrite and only replace "b". but I want to highlight both "a" and "b". how to solve this? I got another problem . If I replace/highlight it then it replace all "a" and "b" of HTML tag. so, how to prevent to replace those html tag. but also when I display the whole text I need all html tag

    var keys = keyword.split(' ');
    //alert(keys);
    for(var i=0; i<keys.length; i++)
        {
        var re = new RegExp(keys[i], "gi");
        oldvar = oldvar.replace(re, '<span style="background-color:#FFFF00">'+keys[i]+'</span>');
        document.getElementById("wordlist").innerHTML=oldvar;
        alert(keys[i]);
        }

Edit: It seems obvious that oldvar is not changed durring the loop always only last replace is applyied. You have to change "oldvar" in order to replace all the words

You can actually do a single regex replace like this:

var re = new RegExp(keys.join("|"), "gi");
oldvar = oldvar.replace(re, replacer);        
document.getElementById("wordlist").innerHTML = oldvar;

function replacer(str)  
{  
    return '<span style="background-color:#FFFF00">' + str + '</span>';
}  

Example - http://jsfiddle.net/zEXrq/1/

What it is doing is merging all keys into a single regex seperated by | which will match all the words then running the replacer function on the matches.

Example 2 - http://jsfiddle.net/zEXrq/2/

You should do the Operations on the same var. You take oldvar outside of the loop, but never take the changed content into oldvar. So the last iteration (only) is the one which replaces the content.

You're calling replace on the variable oldvar (which is not declared in this snippet) in each iteration and thus starting from the same point - the non-highlighted string - every time. Without having seen all of the code, I would guess that simply replacing var NewString = with oldvar = and .innerHTML=NewString with .innerHTML=oldvar will solve your problem.

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