比较 JavaScript 中的部分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13833944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare part of string in JavaScript
提问by user1022521
How do I compare a part of a string - for example if I want to compare if string A is part of string B. I would like to find out this: When string A = "abcd"and string B = "abcdef"it needs to return true. How do I do that in JavaScript? If I use substring(start, end)I do not know what values to pass to the startand endparameters. Any ideas?
如何比较字符串的一部分-例如,如果我想比较,如果字符串A是我想找出这个字符串B的一部分:当string A = "abcd"和string B = "abcdef"它需要返回true。我如何在 JavaScript 中做到这一点?如果我使用,substring(start, end)我不知道将哪些值传递给start和end参数。有任何想法吗?
回答by elclanrs
You can use indexOf:
您可以使用indexOf:
if ( stringB.indexOf( stringA ) > -1 ) {
// String B contains String A
}
回答by pala?н
Like this:
像这样:
var str = "abcdef";
if (str.indexOf("abcd") >= 0)
Note that this is case-sensitive. If you want a case-insensitive search, you can write
请注意,这是区分大小写的。如果你想要一个不区分大小写的搜索,你可以写
if (str.toLowerCase().indexOf("abcd") >= 0)
Or,
或者,
if (/abcd/i.test(str))
And a general version for a case-insensitive search, you can set strings of any case
和一个不区分大小写搜索的通用版本,您可以设置任何大小写的字符串
if (stringA.toLowerCase().indexOf(stringB.toLowerCase()) >= 0)
回答by mix3d
Javascript ES6/ES2015 has String.includes(), which has nearly all browser compatibility except for IE. (But what else is new?)
Javascript ES6/ES2015 具有String.includes(),几乎具有除 IE 之外的所有浏览器兼容性。(但还有什么新东西?)
let string = "abcdef";
string.includes("abcd"); //true
string.includes("aBc"); //false - .includes() is case sensitive
回答by mwag
Using indexOf or match is unnecessarily slow if you are dealing with large strings and you only need to validate the beginning of the string. A better solution is to use startsWith() or its equivalent function-- from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith:
如果您正在处理大字符串并且您只需要验证字符串的开头,那么使用 indexOf 或 match 会不必要地慢。更好的解决方案是使用 startsWith() 或其等效函数——来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
回答by lyomi
"abcdef".indexOf("abcd") !== -1should be okay
"abcdef".indexOf("abcd") !== -1应该没问题
回答by senK
You can try the javascript search also
您也可以尝试 javascript 搜索
if( stringA.search(stringB) > -1){
}
回答by Chung-Min Cheng
Using regular expression might help you.
使用正则表达式可能会对您有所帮助。
var patt = new RegExp(stringA, 'i');
if(stringB.match(patt)){
return true;
}

