首页 > 解决方案 > 大写单词的第一个字母超过3个字符的正则表达式

问题描述

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

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

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

标签: javascriptreactjsregex

解决方案


这里有两个例子。一个用于句子(如 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);


推荐阅读