使用正则表达式表示撇号



我正在使用这个函数

function capitalizeAllWords(str: string) {
return str.replace(/bw/s, letter => letter.toUpperCase());
}

当前结果:男装

要求成绩:男士服装

如何做到这一点?

使用

function capitalizeAllWords(str: string) {
return str.replace(/(?<![w'])w/g, letter => letter.toUpperCase());
}

解释

--------------------------------------------------------------------------------
(?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
[w']                    any character of: word characters (a-z,
A-Z, 0-9, _), '''
--------------------------------------------------------------------------------
)                        end of look-behind
--------------------------------------------------------------------------------
w                       word characters (a-z, A-Z, 0-9, _)

注意g标志替换所有匹配项,而不是s

您可以使用replace方法的回调。

function capitalizeAllWords(str: string) {
return str.replace(/'[a-z]|b([a-z])/g, (m, g1) => g1 ? g1.toUpperCase() : m);
}

捕获要在组1中大写的内容(在示例代码中用g1表示),并匹配要保持不变的内容(示例代码中由m表示)

'[a-z]|b([a-z])

解释

  • '[a-z]匹配'和一个字符a-z
  • |
  • b([a-z])一个字边界b,用于防止部分匹配,并捕获组1中的字符A-z

Regex演示

const regex = /'[a-z]|b([a-z])/g;
const str = "Men's apparel $test";
let res = str.replace(regex, (m, g1) => g1 ? g1.toUpperCase() : m);
console.log(res);