pretty直线前进。在JavaScript中,我需要检查,如果一个字符串包含在一个数组持有的任何子。
Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
推荐答案有什么内置的,将做到这一点给你,你必须写一个函数吧。
There's nothing built-in that will do that for you, you'll have to write a function for it.
如果您的知道的字符串不包含任何,在普通的前pressions特殊的人物,那么你可以欺骗了一下,像这样的:
If you know the strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:
if (new RegExp(substrings.join("|")).test(string)) { // At least one match }这将创建一个普通的前pression这是一个系列... 交替的你正在寻找(例如,一个子|两个),并测试,看看是否有任何人的比赛,但如果任何一个子字符串包含在正则表达式特殊(任何字符 * , [等),你就必须先逃避他们,你最好只是在做枯燥的循环来代替。
...which creates a regular expression that's a series of alternations for the substrings you're looking for (e.g., one|two) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*, [, etc.), you'd have to escape them first and you're better off just doing the boring loop instead.
无偿
更新
在关于这个问题的评论,马丁询问有关新的阵列#地图在ECMAScript5功能。 地图是不是所有的太大的帮助,但部分是:
In a comment on the question, Martin asks about the new Array#map function in ECMAScript5. map isn't all that much help, but some is:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) { // There's at least one }活生生的例子(只适用于现代的浏览器)
Live example (Only works on modern browsers)
你要知道,它确实意味着一些开销,而你只需要它符合ECMAScript5的实现(所以,不是IE7或更早的版本,例如,也许甚至没有IE8),但仍然如果你真的进了那个风格编程...(你可以使用一个ECMAScript5垫片,这个或任何其他几个人的。)
Mind you, it does mean some overhead, and you only have it on ECMAScript5-compliant implementations (so, not IE7 or earlier, for instance; maybe not even IE8), but still if you're really into that style of programming... (And you could use an ECMAScript5 shim, this one or any of several others.)
更多推荐
的JavaScript。检查是否字符串包含的子字符串数组文字
发布评论