javascript - 大写单词的第一个字母超过3个字符的正则表达式
问题描述
我在 React 中编写了一些代码,我想使用 Regex 将单词的第一个字母大写超过 3 个字母,但我对 Regex 感到迷茫,我发现了很多东西,但没有任何效果。有什么建议吗?
正则表达式示例但不起作用
"^[a-z](?=[a-zA-Z'-]{3})|\b[a-zA-Z](?=[a-zA-Z'-]{3,}$)|['-][a-z]"
解决方案
这里有两个例子。一个用于句子(如 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);
推荐阅读
- dialog - Testcafe studio - 如何处理原生对话框
- sql-server - 如何在一个查询中使用 EXISTS 和 NOT EXISTS?
- c# - 如何在asp.net中上传多个Excel文件
- angular - Bootstrap 4 angular 5 navbar 链接未正确对齐
- javascript - vuejs 与 firebase 集成给出“createUser 不是函数”错误
- php - 如何处理这种情况?(用户只能根据注册类型的容量选择一个数量值)
- angular - 使用角度的下拉菜单
- android - 如何在后台检查变量以在达到某个值时执行某些操作?
- jhipster - hipster - 导入 JDL
- pentaho - Pentaho 报表设计器 - 没有出现任何字段