gpt4 book ai didi

Javascript:正则表达式 .test() 用于空白

转载 作者:行者123 更新时间:2023-12-01 03:56:01 25 4
gpt4 key购买 nike

查找任何空白字符时出现奇怪的正则表达式结果

new RegExp('^[^\s]+$').test('aaa');
=> true

这是预料之中的,但随后...

new RegExp('^[^\s]+$').test('aaa  ');
=> true

如何返回 true?

最佳答案

您需要通过\\转义字符串中的\。否则,生成的正则表达式将为 /^[^s]+$/,它匹配除字符串之外的任何内容,包括 s

new RegExp('^[^\\s]+$').test('aaa  ');
<小时/>

或者您可以使用 \S 来匹配除空格之外的任何内容。

new RegExp('^\\S+$').test('aaa  ');
<小时/>

最好直接使用正则表达式,而不是解析正则表达式字符串模式。

/^[^\s]+$/.test('aaa  ');

// or

/^\S+$/.test('aaa ');

关于Javascript:正则表达式 .test() 用于空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42668343/

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