我正在嘗試將字串中每個單詞的首字母大寫。我在網上找到了類似的問題,但似乎沒有人回答我忽略諸如不能、不會、不是這樣的收縮的問題。
這段代碼有效,但它也將收縮中撇號后的字母大寫。
var str = str.replace(/\b\w/g, w => w.toUpperCase())
如果字串包含像 can't 或 won't 這樣的縮寫,它將輸出 Can'T 或 Won'T。
有沒有辦法忽略單詞中間的撇號?我仍然想將由其他標點符號分隔的單詞大寫。例如:
- this_is_an_example -> This_Is_An_Example
- this/is/an/example -> This/Is/An/Example
- this,is,an,example -> This,Is,An,Example
uj5u.com熱心網友回復:
您可以使用
const texts = ["this_can't_be_an_example", 'this/is/an/example', 'this,is,an,example']
for (const text of texts) {
console.log(text, '=>', text.replace(/([\W_]|^)(\w)(?<!\w'\w)/g, (_, x,y) => `${x}${y.toUpperCase()}` ))
}
請參閱正則運算式演示。詳情:
([\W_]|^)- 第 1 組 (x):非字母數字字符或字串開頭(\w)- 第 2 組 (y):一個單詞 char(?<!\w'\w)- 確保 Group 2 值前面沒有單詞 char 和'.
uj5u.com熱心網友回復:
這個正則運算式檢測
- 第一個符號
- 強調
- 空間
/象征- 逗號
- 撇號
只需在帶有|分隔符的串列中添加需要符號
str.replace(/((^|_| |\/|,|')\w)/g, w => w.toUpperCase());
uj5u.com熱心網友回復:
您可以使用否定的lookbehind來確保單詞邊界之前沒有撇號。
(?:\b|(?<=_))檢查單詞之前的單詞邊界或下劃線。
const examples = [
"can't",
"this-is-an-example",
"this.is.an.example",
"this/is/an/example",
"this_is_an_example",
"this,is,an,example",
];
examples.forEach(example => {
console.log(example.replace(/(?<!')(?:\b|(?<=_))\w/g, w => w.toUpperCase()));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436143.html
標籤:javascript 正则表达式 细绳 常规语言 大写
