【问题标题】:capitalize first letter of word more than 3 character Regex大写单词的第一个字母超过3个字符的正则表达式
【发布时间】:2021-11-30 07:43:43
【问题描述】:

我在 React 中编写了一些代码,我想使用 Regex 使用 Regex 将超过 3 个字母的单词的首字母大写,但我对 Regex 迷失了方向,我发现了很多东西,但没有任何效果。有什么建议吗?

正则表达式示例但不起作用

"^[a-z](?=[a-zA-Z'-]{3})|\b[a-zA-Z](?=[a-zA-Z'-]{3,}$)|['-][a-z]"

【问题讨论】:

  • 似乎在这里工作:regex101.com/r/mvR2aN/1
  • 您的正则表达式有 3 种替代方法来匹配单个小写字符。您可以使用替换回调函数将匹配大写。

标签: javascript reactjs regex


【解决方案1】:

这里有两个例子。一个用于句子(如 AidOnline01 的答案,但使用String#replaceAll),另一个用于仅使用单词时。

但是,当仅使用单词时,您也可以检查 length 而不是使用正则表达式。

const sentence = "This is a sentence with a few words which should be capitialized";
const word = "capitialized";

// use String#replaceAll to replace all words in a sentence
const sentenceResult = sentence.replaceAll(/\w{4,}/g, word => word[0].toUpperCase() + word.slice(1));

// use String#replace for a single word
const wordResult = word.replace(/\w{4,}/, word => word[0].toUpperCase() + word.slice(1));

console.log(sentenceResult);
console.log(wordResult);

【讨论】:

  • 很好的答案,我认为这比我的要好:)
【解决方案2】:

\w{4,} - 此正则表达式将匹配所有超过 3 个字母的单词

let str = "this is Just an long string with long and short words";

const matches = str.matchAll(/\w{4,}/g);

for(match of matches) {
  str = str.substring(0, match.index) + match[0].charAt(0).toUpperCase() + match[0].slice(1) + str.substring(match.index + match[0].length);
}

console.log(str);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多