Basically, I need to be able to find certain words (by 'word' I mean a set of characters) in a string (case insensitive) and if they match, I need to insert a symbol after the first letter of that particular set of characters. I can't use search replace, as that would not preserve the case.
Example:
Brown brownies are in an oven.
If the word I'm looking for is brown
, and the character I want to insert is *
, the result should be:
B*rown b*rownies are in an oven.
What is the best way to do so in JS?
Basically, I need to be able to find certain words (by 'word' I mean a set of characters) in a string (case insensitive) and if they match, I need to insert a symbol after the first letter of that particular set of characters. I can't use search replace, as that would not preserve the case.
Example:
Brown brownies are in an oven.
If the word I'm looking for is brown
, and the character I want to insert is *
, the result should be:
B*rown b*rownies are in an oven.
What is the best way to do so in JS?
Share Improve this question asked Aug 8, 2011 at 22:37 krbkrb 16.4k29 gold badges114 silver badges186 bronze badges4 Answers
Reset to default 7Regex with option 'ig' does the trick.
"Brown brownies are in an oven.".replace(/(b)(rown)/gi, "$1*$2")
function astAfterFirstLetter(words) {
var re = new RegExp("\\b(?=" + words.join("|") + "\\b)(\\w)(\\w*)", "gi");
return function (str) { return str.replace(re, "$1*$2"); };
}
astAfterFirstLetter(["brown", "cow"])("How now brown cow!")
produces
How now b*rown c*ow!
You can use regex, something like:
var re = /(B)(rown)/gi;
console.log("Brown brownies are in an oven".replace(re, "$1*$2"));
var str = 'Brown brownies are in an oven.'
var s = 'brown';
var r = '*';
var re = new RegExp('('+s.substr(0,1)+')('+s.substr(1)+')','ig');
log(str.replace(re, '$1'+r+'$2'));
But you will need to watch s
for the characters that have some special meaning to regular expressions (https://developer.mozilla/en/JavaScript/Reference/Global_Objects/regexp) and will need to take care setting r
too. Will fail also if s
's length is less than 2.