How to replace several words in javascript
I wanna rep开发者_JAVA百科lace several words in a text using replace()
in javascript, how can I do that?
For example, if I wanna replace, 'Dave Chambers, David Chambers, Will Smith' with 'Jackie Chan', no matter if they're in upper-case or lower-case, do I have to keep repeating the replace()
method on the same string variable everytime, i.e.
var str = sometext.innerHTML;
str.replace('Dave Chambers', 'Jackie Chan');
str.replace('David Chambers', 'Jackie Chan');
str.replace('Will Smith', 'Jackie Chan');
Use a regular expression with the alternator (|
) and case insensitive modifier (/i
):
var str = sometext.innerHTML,
reg = /Dave Chambers|David Chambers|Will Smith/i;
str = str.replace(reg, "Jackie Chan");
A shorter, more complex regex could be:
/Dav(?:e|id) Chambers|Will Smith/i;
And if there may be more than 1 occurrence, add the global modifier (g
) to replace all:
/Dav(?:e|id) Chambers|Will Smith/ig;
You can learn more about regular expressions here, or by searching Google. You can see a working demo here.
This function will replace any words you want in a string.
function wordInString(s, words, replacement){
var re = new RegExp( '\\b' + words.join('|') + '\\b','gi');
return s.replace(re, replacement);
}
// usage:
var str = 'did you, or did you not, get why?';
str = wordInString(str, ['YOU', 'get'], 'XXX');
console.log(str); // "did XXX, or did XXX not, XXX why?"
str.replace(/(Dav(e|id) Chambers)|(Will Smith)/ig, 'Jackie Chan');
You'll want to use regular expressions if you want to ignore case:
var str = sometext.innerHTML;
str.replace(/Dave Chambers/ig, 'Jackie Chan')
.replace(/David Chambers/ig, 'Jackie Chan')
.replace(/Will Smith/ig, 'Jackie Chan');
You can do it all in one statement like above and that's how I would prefer as it's more readable.
vsync's answer helped me to highlight a word in whole innerHTML
. This could be used for the question and for many other things, thanks!
function highlightWord(word) {
// get your current div content by id
var string = document.getElementById('your-id').innerHTML;
// set word to highlight
var newWord = '<mark>' + word + '</mark>';
// do replacement with regular expression
var allWords = new RegExp( '\\b' + word + '\\b','gi');
var newString = string.replace(allWords, newWord);
// set your new div content by id
document.getElementById('your-id').innerHTML = newString;
};
If you want to make some array to array replace, respecting the separators like "." or ",", I have created something like that that may help you.
function arrayReplace( text, arrFrom, arrTo, caseSensitive ) {
return text.
replace(/</g," <<").
replace(/>/g,">> ").
replace(/([\.\;\,])/g," <$1> ").
split(" ").
map(
function(value) {
var pos = arrFrom.indexOf( caseSensitive ? value : value.toLowerCase() );
if( pos == -1 ) {
return value;
} else {
return arrTo[pos % arrTo.length];
}
}
).
join(" ").
replace(/( \<|\> )/g,"");
};
console.log(
arrayReplace(
"First example. Trivial case",
[ "example", "case"],
[ "demo", "test" ]
)
); // First demo. Trivial test
console.log(
arrayReplace(
"Leaving earth, passing close to the sun, going to the moon.",
[ "earth", "sun", "moon"],
[ "EARTH", "SUN", "MOON"]
)
); // Leaving EARTH, passing close to the SUN, going to the MOON.
console.log(
arrayReplace(
"Leaving earth, passing close to the sun, going to the moon.",
[ "earth", "sun", "moon"],
[ "PLANET"]
)
); // Leaving PLANET, passing close to the PLANET, going to the PLANET.
console.log(
arrayReplace(
"Leaving earth, passing close to the sun, going to the moon.",
[ "earth", "sun", "moon"],
[ "PLANET", "STAR" ]
)
); // Leaving PLANET, passing close to the STAR, going to the PLANET.
console.log(
arrayReplace(
"Rain rain, goes away, no one wants you any way.",
[ "rain", "a"],
[ "pig", "x"]
)
);
// pig pig, goes away, no one wants you any way.
console.log(
arrayReplace(
"Testing the <<function>>. Replacing, in <any> case. Even <the ;funny; ones>.",
[ "funny", "even", "function" ],
[ "complex", "including", "code" ]
)
); // Testing the <<code>>. Replacing, in <any> case. including <the ;complex; ones>.
精彩评论