1) 从几到题开始,

a. 千分位 10000000 => 10,000,000

note:

  • a(?=x) 仅匹配a后面跟着的x, ax. =. x
  • a(?:\d{3}) 仅仅作为匹配, 不做记忆。
  • (a) 作为匹配的结果

 1 '10000000'.replace(/(\d)?=((?:\d{3})+)$/g, '$1,')  

 

b. 姓和名交换。 ‘John, dee’ => 'Dee John'

'John, dee'.replace(/(\w+)\s+,\s+(\w+)/g, '$2 $1')

'John, dee'.replace(/(\w+)\s+,\s+(\w+)/g, (l1, l2)=>{
   const L1 =  l1.replace(/^\w/g, i=>i.toUpperCase() )
    const L2 =  l2.replace(/^\w/g, i=>i.toUpperCase() )
   return `${L2} ${L1}`;
})

  

c. 2020-08变成日期格式Aug, 2020. 

let arr= '2020-08'.match(/\d{1,4}/g);
arr[1]++;
return new Date(arr)

  

 2) 找到并突出一个模式的所有实例

在一个循环中, 使用RegExp exec方法和全局标志(g, 来找到一个模式的所有实例。

其实:

index:找到匹配的索引

input:最初的输入字符串

[0]: 匹配的值

[1]...[n]: 带圆括号的子字符串匹配

如 re = /a(p+).*(pie)/g

re.exec('The apple is a  app pie')

['apple is a app pie', 'pp', 'pie']

var searchString = 'Now is the time and this is the time and that is the time';
var pattern = /t\w*e/g;
var matched;
var str = '';

while((matched = pattern.exec(searchString))!=null){
    str += 'at '=matched.index+" we found "+matched[0]+'\n';
}
console.log(str);

  

posted on 2021-02-18 22:45  connie313  阅读(29)  评论(0编辑  收藏  举报