正则表达式的function
设定正则表达式
let re;
re = /hello/;
i ——不区分大小写
re = /hello/i; //正则表达式
//加入i则可匹配大小写 i= case insensitive
g ——匹配全局的re
re = /hello/g; // Global search
re.source——得到内容
console.log(re);
console.log(re.source);
re的方法
exec()
re.exec()
//exec() - Return result in an array or null
const result = re.exec('brad helloworld hello ');
console.log(result);
console.log(result[0]);
console.log(result['index']);
console.log(result.input);
test()
re.test()
返回true / false;
//test() - Returns true or false
const result2 = re.test('Gello Hello');
console.log(result2);
str的方法
str.match()
str.match 返回与exec相同;
//match() - Returns result array or null
const str = 'hello there hello hello';
const result3=str.match(re); //match——把re传给str exec——把str传给re
console.log(result3);
str.search()
返回下标;
//search() - Returns index of the first match if not found returns -1
const str2 = 'brad Hello there';
const result4= str2.search(re);
console.log(result4); //search得到index
str.replace()
返回替换所有re后的str;
//replace() - Return new string with some or all matches of a pattern
const str3 = 'Hello there';
const newstring = str3.replace(re,'hi'); //返回替换后的string
console.log(newstring);