js中字符串和正則相關的方法


正則表達式對象常用方法

test()

檢索字符串中指定的值。返回 true 或 false。

var str="Embrace You"
var r1=/you/i.test(str)//i 忽略大小寫
console.log(r1)//true

支持正則表達式的String對象的方法

split()

  • 可以將一個字符串拆分為一個數組
  • 方法中可以傳遞一個正則表達式作為參數,這樣方法將會根據正則表達式去拆分字符串
var str="1a2B3d4g5c6"
var result=str.split(/[A-z]/)
console.log(result)//["1", "2", "3", "4", "5", "6"]

search()

  • 可以搜索字符串中是否含有指定內容
  • 如果搜索到指定內容,則會返回第一次出現的索引,如果沒有搜索到,返回-1
  • 它可以接收一個正則表達式作為參數,然后根據正則表達式去檢索字符串

例:搜索字符串中是否含有abc 或 aec 或 afc

var str1="hello abc hello aec sdf afc"
var str2="hello hello aec sdf afc"
var result1=str1.search(/a[bef]c/)
var result2=str2.search(/a[bef]c/)
console.log(result1+" "+result2)//6 12

match()

語法:

string.match(searchvalue)

在字符串中查找 "ain":

var str="The rain in SPAIN stays mainly in the plain"; 
var n=str.match("ain");//ain

找到一個便停止查找,若要全部找出,可配合使用正則表達式:

var str="The rain in SPAIN stays mainly in the plain"; 
var n=str.match(/ain/gi);//全局查找,忽略大小寫
//ain,AIN,ain,ain

replace()

語法:

string.replace(searchvalue,newvalue)

在字符串中查找並替換“Microsoft”:

 

var str="Visit Microsoft! Visit Microsoft!";
var n=str.replace("Microsoft","Runoob");
//n:"Visit Runoob! Visit Microsoft!"

 

此時只替換了第一處的值,若想繼續替換,可使用正則表達式

var str="Visit Microsoft! Visit Microsoft!";
var n=str.replace(/Microsoft/gi,"Runoob");//全局替換,忽略大小寫
//n: "Visit Runoob! Visit Runoob!"

 


免責聲明!

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



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