简体   繁体   English

JavaScript中带有正则表达式的意外结果

[英]Unexpected result with Regular Expression in JavaScript

This is my String. 这是我的弦。

 var re = "i have a string";

And this my expression 这是我的表情

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

I want that it will make the the first character of any word to Uppercase. 我希望它将使所有单词的第一个字符变为大写。 But the replacement above return only the first character uppercased. 但是上面的替换仅返回大写的第一个字符。 But I have added /g at the last. 但是我最后添加了/ g。


Where is my problem? 我的问题在哪里?

You can use the \\b to mark a boundary to the expression. 您可以使用\\b标记表达式的边界。

 const re = 'i am a string'; console.log(re.replace(/(\\b[az])/g, (x) => x.toUpperCase())); 

The metacharacter \\b is an anchor like the caret and the dollar sign. 元字符\\ b是类似于插入符号和美元符号的锚。 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. 字符串中的两个字符之间,其中一个是单词字符,另一个不是单词字符。

Vlaz的评论对我来说似乎是正确的答案-通过在样式的开头加上“ ^”,可以确保只找到第一个字符-尽管“ / g”,因为它们没有立即跟随行的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM