js 正则表达式的6个函数

str = 'hello world!';  
//1
//(1 正则表达字面量,这种直接是常量的表示用法可以让js解析器提高性能
var result = /^hello/.test(str);   //test 返回一个 Boolean 值,它指出在被查找的字符串中是否匹配给出的正则表达式。true false
console.log(result)

//(2 构造函数,这种方式可以在runtime的时候动态确定正则是什么,更加灵活
re = new RegExp('^hello')  
console.log(re.test('hello world!'));

//--------------------------
//2 注意对于每个正则对象的exec每次调用都只返回一个匹配,如果需要拿到全部匹配就需要while循环获取,循环结束标志是返回值为null
myRe = /d(b+)d/g;  

console.log(myRe.exec('cdbbdbsdbdbz') )
// ["dbbd", "bb", index: 1, input: "cdbbdbsdbdbz"]  

console.log(myRe.exec('cdbbdbsdbdbz')) 
// ["dbd", "b", index: 7, input: "cdbbdbsdbdbz"]  

console.log(myRe.exec('cdbbdbsdbdbz'))
 //------------------------------
 //3 string的match ,如果是global匹配则出所有匹配的数组,如果不是,则出第一个匹配的字符串,以及相应的捕获内容


 console.log('cdbbdbsdbdbz'.match(/d(b+)d/g)) // ["dbbd", "dbd"]  

 console.log('cdbbdbsdbdbz'.match(/d(b+)d/)) // ["dbbd", "bb", index: 1, input: "cdbbdbsdbdbz"]  



 str = 'hello world!';  

 var result = /^hello/.test(str); // true  
 
 'cdbbdbsdbdbz'.search(/d(b+)d/) // 1    返回与正则表达式查找内容匹配的第一个子字符串的位置(偏移位)
 
 'xxx'.search(/d(b+)d/) // -1 没有匹配  
 
 var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';  
 
 var re = /\s*;\s*/;  
 
 var nameList = names.split(re);  
 
 // [ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand " ]
 
 var re = /apples/gi;  
 
 var str = 'Apples are round, and apples are juicy.';  
 
 var newstr = str.replace(re, 'oranges');  
 //这个replace方法的用法着实比较多,只放了最基础用法,当有需求的时候再查就好了,整体有概念了再实践比强行记忆要好吧~

//在线匹配

https://blog.csdn.net/vM199zkg3Y7150u5/article/details/79338818

https://blog.csdn.net/guo273559625/article/details/78085797

posted @ 2019-07-05 14:41  cnchengv  阅读(270)  评论(0)    收藏  举报