最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript case-insensitive matching and replacing? - Stack Overflow

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论