繁体   English   中英

使用正则表达式检查以子字符串开头的字符串

[英]Check string starting with substring using regex

尝试检查randomString是否以randomString开头just. (包括点)。

这应该给我错误,但事实并非如此:

 var randomString = 'justanother.string'; var a = randomString.match('^just\\.'); console.log(a); 

我可能错过了正则表达式参数中的某些内容。

您需要使用创建正则表达式和use .test()方法。

 var randomString = 'justanother.string'; var a = /^just\\./.test(randomString) console.log(a); 

答案很简单,您没有正确创建正则表达式。
'this is not regex'
/this is regex/ new RexExp('this is also regex')

 var randomString = 'justanother.string'; var a = randomString.match(/^just\\./); console.log(a); // I sugest dooing something like this const startsWithJust = (string) => /^just\\./.test(string) 

 var randomString = 'justanother.string'; var another = 'just.....................'; console.log( randomString.match('^(just[.]).*') ); console.log( another.match('^just[.].*') ); 

如果您希望保持一致,则只需更改一项即可。

var a = randomString.match('^just\\.');

您需要转义第一个反斜杠。

暂无
暂无

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

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