开发者

Javascript case-insensitive matching and replacing?

Basically, I need to be able to find certain words (by 'word' I mean a set of characters) in a开发者_StackOverflow 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?


Regex 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.org/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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜