Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中检查字符串是否包含子字符串?(How to check whether a string contains a substring in JavaScript?)

Usually I would expect a String.contains() method, but there doesn't seem to be one.

(通常我希望使用String.contains()方法,但是似乎没有。)

What is a reasonable way to check for this?

(有什么合理的方法来检查?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ECMAScript 6 introduced String.prototype.includes :

(ECMAScript 6引入了String.prototype.includes :)

 var string = "foo", substring = "oo"; console.log(string.includes(substring)); 

includes doesn't have Internet Explorer support , though.

(includes 不支持Internet Explorer 。)

In ECMAScript 5 or older environments, use String.prototype.indexOf , which returns -1 when a substring cannot be found:

(在ECMAScript 5或更旧的环境中,使用String.prototype.indexOf ,如果找不到子字符串,则返回-1:)

 var string = "foo", substring = "oo"; console.log(string.indexOf(substring) !== -1); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...