gpt4 book ai didi

javascript - 正则表达式将所有单词转为大写,但排除 '(撇号)

转载 作者:行者123 更新时间:2023-12-02 22:45:40 25 4
gpt4 key购买 nike

我正在尝试构建一个将所有字符串单词大写的函数,但我遇到了以下问题:

String.prototype.upper = function() {
return this.replace(/[^a-zA-Z0-9]+(.)/g, chr => chr.toUpperCase())
}


let str = "My uncle's car is red";
console.log(str.upper())


//My Uncle'S Car Is Red

我需要将撇号后面的 S 排除在大写形式之外。

有什么想法可以做到这一点吗?

谢谢

最佳答案

我会将正则表达式更改为 \s+\w 以搜索空格和/或制表符后的字母。

const upper = (input) => input.replace(/\s+\w/g, x => x.toUpperCase());
console.log(upper("My uncle's car is red"));

关于javascript - 正则表达式将所有单词转为大写,但排除 '(撇号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58410648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com