的JavaScript。检查是否字符串包含的子字符串数组文字

编程入门 行业动态 更新时间:2024-10-15 00:20:03
本文介绍了的JavaScript。检查是否字符串包含的子字符串数组文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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。检查是否字符串包含的子字符串数组文字

本文发布于:2023-10-27 10:30:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数组   文字   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!