首页 文章

将每个单词的首字母大写,\ b \ w也适用于我

提问于
浏览
5

需要将句子中每个单词的第一个字母大写,但是我的正则表达式也是我在'm'中的大写字母 .

完整的表达是这样的:

/(?:^\w|[A-Z]|\b\w)/g

这里的问题(我认为)是 \b\w 会 grab 单词边界后面的第一个字母 . 我假设单引号表示单词边界,因此也将 I'mm 大写为 I'M .

任何人都可以帮我改变表达式,在单引号后排除'm'吗?

提前致谢 .

1 回答

  • 2

    在语言中间找到真正的单词中断可能会更多一些
    比使用正则表达式边界更复杂 .

    ( \s* [\W_]* )           # (1), Not letters/numbers,
     ( [^\W_] )               # (2), Followed by letter/number
     (                        # (3 start)
          (?:                      # -----------
               \w                       # Letter/number or _
            |                         # or,
               [[:punct:]_-]            # Punctuation
               (?= [\w[:punct:]-] )     #  if followed by punctuation/letter/number or '-'
            |                         #or,
               [?.!]                    # (Add) Special word ending punctuation
          )*                       # ----------- 0 to many times
     )                        # (3 end)
    
    var str = 'This "is the ,input _str,ng, the End ';
    console.log(str);
    console.log(str.replace(/(\s*[\W_]*)([^\W_])((?:\w|[[:punct:]_-](?=[\w[:punct:]-])|[?.!])*)/g, function( match, p1,p2,p3) {return p1 + p2.toUpperCase() + p3;}));
    

相关问题