JavaScript:indexOf与搜索字符串时匹配? [英] JavaScript: indexOf vs. Match when Searching Strings?

查看:1059
本文介绍了JavaScript:indexOf与搜索字符串时匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了可读性之外,使用

str.indexOf("src") 

str.match(/src/)

我个人更喜欢匹配(和regexp)但是同事似乎走了另一条道路。我们想知道它是否重要......?

I personally prefer match (and regexp) but colleagues seem to go the other way. We were wondering if it mattered ...?

编辑:

我应该在一开始就说过这是为了进行部分普通字符串匹配(在JQuery的类属性中获取标识符)而不是使用通配符等进行完整正则表达式搜索的函数。

I should have said at the outset that this is for functions that will be doing partial plain-string matching (to pick up identifiers in class attributes for JQuery) rather than full regexp searches with wildcards etc.

class='redBorder DisablesGuiClass-2345-2d73-83hf-8293' 

所以它的区别在于:

string.indexOf('DisablesGuiClass-');

VS

string.match(/DisablesGuiClass-/)


推荐答案

RegExp确实比indexOf慢(你可以看到它这里),虽然通常这应该不是问题。使用RegExp,你还必须确保字符串被正确转义,这是一个值得思考的额外事情。

RegExp is indeed slower than indexOf (you can see it here), though normally this shouldn't be an issue. With RegExp, you also have to make sure the string is properly escaped, which is an extra thing to think about.

除了两个工具之外,还有两个问题你需要什么,为什么不选择更简单的?

Both of those issues aside, if two tools do exactly what you need them to, why not choose the simpler one?

这篇关于JavaScript:indexOf与搜索字符串时匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆