gpt4 book ai didi

javascript - javascript错误中的startwith

转载 作者:行者123 更新时间:2023-12-02 05:46:26 24 4
gpt4 key购买 nike

我在 Javascript 中使用 startswith reg exp

if ((words).match("^" + string)) 

但是如果我输入像 , ] [\/ 这样的字符,Javascript 会抛出异常。有什么想法吗?

最佳答案

如果您使用正则表达式进行匹配,则必须确保传递有效的 Regular Expression匹配()。检查list of special characters以确保您没有传递无效的正则表达式。以下字符应始终进行转义(在其前面放置一个\):[\^$.|?*+()

更好的解决方案是像这样使用 substr():

if( str === words.substr( 0, str.length ) ) {
// match
}

或者使用 indexOf 的解决方案是(看起来更干净一些):

if( 0 === words.indexOf( str ) ) {
// match
}

接下来,您可以将 startsWith() 方法添加到包含上述两种解决方案中的任何一种的字符串原型(prototype),以提高用法的可读性:

String.prototype.startsWith = function(str) {
return ( str === this.substr( 0, str.length ) );
}

添加到原型(prototype)后,您可以像这样使用它:

words.startsWith( "word" );

关于javascript - javascript错误中的startwith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1409476/

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