[英]How can I make javascript match the start of a string?
I have the following coce: 我有以下情况:
if (link.action === "Create") {
However my link.action could be: 但是我的link.action可能是:
Create xxxx
Is there a way I can change this match so it just checks for the start being "Create" ? 有没有一种方法可以更改此匹配项,以便仅检查开始位置为“创建”?
Just Check string.indexOf(string_to_check)
. 只需检查string.indexOf(string_to_check)
。 It returns the index number for a 'string_to_check', if it exists in the string. 如果字符串中存在“ string_to_check”,则它返回索引号。 Any in your case, you want the string start with "Create", so the index should be always 0 in your case. 任何情况下,您都希望字符串以“ Create”开头,因此索引应始终为0。
So, You can try this 所以,你可以试试这个
if (link.action.indexOf("Create") == 0) {
Use a regular expression . 使用正则表达式 。
if (link.action.match(/^Create/) {
}
^
is a special character: an anchor which matches only the beginning of the input. ^
是一个特殊字符:仅匹配输入开头的锚。
More reading on regex in general: http://www.regular-expressions.info 一般而言, 请阅读有关正则表达式的更多信息: http : //www.regular-expressions.info
link.action.slice(0,6)=="Create"
Will also work as you like as above mentioned methods. 您也可以按照上述方法工作。 For further read String object reference in java script . 要进一步阅读Java脚本中的String对象参考 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.