Javascript case-insensitive matching and replacing? - Stack Overflow

Basically, I need to be able to find certain words (by 'word' I mean a set of characters) in

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 badges
Add a ment  | 

4 Answers 4

Reset to default 7

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

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

相关推荐

  • Javascript case-insensitive matching and replacing? - Stack Overflow

    Basically, I need to be able to find certain words (by 'word' I mean a set of characters) in

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信