js 查找字符串中是否包含指定的字符串


1、indexOf()
var str = "123"; 
console.log(str.indexOf("3") != -1 ); // true
indexOf() 方法可返回某個指定的字符串值在字符串中首次出現的位置。如果要檢索的字符串值 沒有找到,則該方法返回 -1
2、includes()
var str = "Hello world, welcome to the Runoob。"; 
var n = str.includes("world"); //true
includes() 方法用於判斷字符串是否包含指定的子字符串,如果找到匹配的字符串則返回 true,否則返回 false。注意: includes() 方法區分大小寫。
3、search()
var str="Visit W3School!" 
console.log(str.search(/W3School/)) //6 

var str="Visit W3School!"
console.log(str.search('W3School')) //6
search() 方法用於檢索字符串中指定的子字符串,或檢索與正則表達式相匹配的子字符串。如果匹配到字符串則返回,字符串所在索引。
4、match()
var str="The rain in SPAIN stays mainly in the plain"; 
var n=str.match(/ain/g); // ain,ain,ain
match() 方法可在字符串內檢索指定的值,或找到一個或多個正則表達式的匹配。注意: includes() 方法不區分大小寫。
5、test()
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { 
    console.log("移動") 
} else { 
    console.log("PC") 
} 

var str="Hello world!";
//查找"Hello"
var patt=/Hello/g; 
var result=patt.test(str); 
console.log(result) // true
test() 方法用於檢測一個字符串是否匹配某個模式。如果字符串中有匹配的值返回 true ,否則返回 false。
6、exec()
var str="Hello world!"; 
//查找"Hello" 
var patt=/Hello/g; 
var result=patt.exec(str); 
console.log(result) // Hello
exec() 方法用於檢索字符串中的正則表達式的匹配。如果字符串中有匹配的值返回該匹配值,否則返回 null。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM