通常我会期待一个 String.contains()
方法,但似乎没有。
检查这个的合理方法是什么?
通常我会期待一个 String.contains()
方法,但似乎没有。
检查这个的合理方法是什么?
以下列出了当前的可能性:
1.(ES6) includes
- 去回答
var string = "foo",
substring = "oo";
string.includes(substring);
2. ES5和更老 indexOf
var string = "foo",
substring = "oo";
string.indexOf(substring) !== -1;
String.prototype.indexOf
返回另一个字符串中字符串的位置。如果没有找到,它将返回 -1
。
3。 search
- 去回答
var string = "foo",
expr = /oo/;
string.search(expr);
4. lodash包括 - 去回答
var string = "foo",
substring = "oo";
_.includes(string, substring);
5. RegExp - 去回答
var string = "foo",
expr = /oo/; // no quotes here
expr.test(string);
6.匹配 - 去回答
var string = "foo",
expr = /oo/;
string.match(expr);
性能测试 显示出来 indexOf
可能是最好的选择,如果它涉及速度问题。
你可以轻松添加一个 contains
使用此语句的String方法:
String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
注意: 请参阅下面的注释,了解不使用此参数的有效参数。我的建议:用你自己的判断。
或者:
if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; }
您的代码存在的问题是JavaScript区分大小写。你的方法调用
indexof()
应该是
indexOf()
尝试修复它,看看是否有帮助:
if (test.indexOf("title") !=-1) {
alert(elm);
foundLinks++;
}
"potato".includes("to");
> true
请注意,您可能需要加载 es6-shim
或者类似于在旧版浏览器上使用它。
require('es6-shim')
var index = haystack.indexOf(needle);
你可以使用JavaScript search()
方法。
语法是: string.search(regexp)
它返回匹配的位置,如果未找到匹配则返回-1。
见那里的例子: jsref_search
您不需要复杂的正则表达式语法。如果你不熟悉它们就简单了 st.search("title")
会做。如果您希望测试不区分大小写,那么您应该这样做 st.search(/title/i)
。
String.prototype.includes()
在ES6中引入。
确定是否可以在另一个字符串中找到一个字符串, 适当地返回true或false。
var contained = str.includes(searchString [, position]);
searchString
要在此字符串中搜索的字符串。
position
此字符串中开始搜索的位置 searchString
默认为0。
var str = "To be, or not to be, that is the question.";
console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("To be", 1)); // false
这可能需要旧版浏览器中的ES6垫片。
如果你正在寻找一种替代方法来编写丑陋的-1检查,那么你可以先添加一个〜代替。
if (~haystack.indexOf('needle')) alert('found');
乔齐默尔曼 - 你会看到使用~on -1将其转换为0.数字0是a falsey值,表示转换为false时将评估为false 一个布尔值。这可能看起来不是一个很大的洞察力,但是 记住,当查询不是时,indexOf之类的函数将返回-1 找到。这意味着不要写类似于此的东西:
if (someStr.indexOf("a") >= 0) { // Found it } else { // Not Found }
您现在可以在代码中使用更少的字符,以便您可以编写它 喜欢这个:
if (~someStr.indexOf("a")) { // Found it } else { // Not Found }
更多 详情请点击
这段代码应该运行良好:
var str="This is testing for javascript search !!!";
if(str.search("for") != -1) {
//logic
}
写一个常用的方法 contains
JavaScript中的方法 是:
if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}
按位求反运算符(~
)用来转 -1
成 0
(falsey),所有其他值都将为非零(真实)。
double boolean negation运算符用于将数字转换为布尔值。