【问题标题】:Regex to Upper Case all words but exclude ' (apostrophe)正则表达式为大写所有单词,但不包括 '(撇号)
【发布时间】:2020-02-13 01:51:53
【问题描述】:

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

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 为大写字母。

任何想法如何做到这一点?

谢谢

【问题讨论】:

  • 只需在字符类中添加'即可使其成为/[^a-zA-Z0-9']+(.)/g
  • 我怀疑添加' 是唯一要做的事情。只有当s 之后没有字符字符并且' 之前有一个字母时,您才应该避免匹配's
  • o'connor's car is red 的结果应该是什么?
  • 试试/(?<![-\p{L}0-9])\p{Ll}(?<!\p{L}'s(?![\p{L}0-9]))/gu

标签: javascript regex function uppercase apostrophe


【解决方案1】:

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

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

【讨论】:

  • 它在编辑器上工作,但在 Codewars 上发生冲突。不知道为什么。寻求帮助。让我们看看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
相关资源
最近更新 更多