gpt4 book ai didi

javascript - JavaScript 中的正则表达式出现意外结果

转载 作者:行者123 更新时间:2023-11-28 17:39:10 28 4
gpt4 key购买 nike

这是我的字符串。

 var re = "i have a string";

这就是我的表情

var str = re.replace(/(^[a-z])/g, function(x){return x.toUpperCase();});

我希望它将任何单词的第一个字符变为大写。但上面的替换仅返回第一个大写字符。但我在最后添加了/g。

<小时/>

我的问题出在哪里?

最佳答案

您可以使用\b来标记表达式的边界。

const re = 'i am a string';

console.log(re.replace(/(\b[a-z])/g, (x) => x.toUpperCase()));

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  1. Before the first character in the string, if the first character is a word character.
  2. After the last character in the string, if the last character is a word character.
  3. Between two characters in the string, where one is a word character and the other is not a word character.

关于javascript - JavaScript 中的正则表达式出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48357965/

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