RegExp 匹配时如何忽略空格
在正则表达式中,可以使用\s来匹配空白字符,包括空格、制表符、换行符等。如果要忽略空格,可以在正则表达式中使用\s*来匹配0个或多个空格。例如:
var str = ' hello world ';
var pattern = /hello\s*world/;
console.log(pattern.test(str)); // true
在上面的例子中,\s*可以匹配hello和world之间的任意数量的空格,因此可以匹配到' hello world '这个字符串。
另外,如果要忽略字符串两端的空格,可以使用trim()方法:
var str = ' hello world ';
console.log(str.trim()); // 'hello world'
原文地址: https://www.cveoy.top/t/topic/loFn 著作权归作者所有。请勿转载和采集!