比较JavaScript中的部分字符串

use*_*521 17 javascript string

我如何比较字符串的一部分-例如,如果我想比较,如果字符串A是我想找出这个字符串B的一部分:当string A = "abcd"string B = "abcdef"它需要返回true.我如何在JavaScript中执行此操作?如果我使用substring(start, end)我不知道传递给startend参数的值.有任何想法吗?

elc*_*nrs 19

你可以使用indexOf:

if ( stringB.indexOf( stringA ) > -1 ) {
  // String B contains String A
} 
Run Code Online (Sandbox Code Playgroud)


pal*_*aѕн 12

像这样:

var str = "abcdef";
if (str.indexOf("abcd") >= 0)
Run Code Online (Sandbox Code Playgroud)

请注意,这是区分大小写的.如果您想要不区分大小写的搜索,可以编写

if (str.toLowerCase().indexOf("abcd") >= 0)
Run Code Online (Sandbox Code Playgroud)

要么,

if (/abcd/i.test(str))
Run Code Online (Sandbox Code Playgroud)

对于不区分大小写的搜索的通用版本,您可以设置任何大小写的字符串

if (stringA.toLowerCase().indexOf(stringB.toLowerCase()) >= 0)
Run Code Online (Sandbox Code Playgroud)


mix*_*x3d 7

Javascript ES6 / ES2015具有String.includes()除了IE之外,几乎具有所有浏览器兼容性。(但是还有什么新东西?)

let string = "abcdef";
string.includes("abcd"); //true
string.includes("aBc"); //false - .includes() is case sensitive
Run Code Online (Sandbox Code Playgroud)

  • 这就是为什么神给了我们巴别塔。 (2认同)

mwa*_*wag 5

如果您正在处理大字符串并且只需要验证字符串的开头,那么使用 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;
  };
}
Run Code Online (Sandbox Code Playgroud)


lyo*_*omi 3

"abcdef".indexOf("abcd") !== -1应该没问题