Javascript jquery 检查字符串是否以 1234 开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8073510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:37:35  来源:igfitidea点击:

jquery check if string starts with 1234

javascriptjquery

提问by Dragan

Thanks for taking the time to answer my question.

感谢您抽出时间回答我的问题。

I want to check if a string has exactly 7 characters and starts with "1234". How do I do that?

我想检查一个字符串是否正好有 7 个字符并以“1234”开头。我怎么做?

I know of string.substring but am not sure if I shouold use regex or are there any other alternative. Thanks in advance!

我知道 string.substring 但我不确定我是否应该使用正则表达式或者还有其他选择。提前致谢!

回答by gilly3

Simple RegExp:

简单的正则表达式:

var isMatch = /^1234...$/.test(myString);

Or:

或者:

var isMatch = myString.length == 7 && myString.indexOf("1234") == 0;

Edit:Or:

编辑:或:

var isMatch = myString.length == 7 && myString.substr(0, 4) == "1234";