github.com/shfshanyue/… , and the big factory surface and internal promotion information

If you want to replace a String in full, you can use string.prototype. replace(re, replacer), where global Flag is enabled for regular expressions

const s = 'foo foo foo'
s.replce(/foo/g.'bar')
Copy the code

Can regular expressions be used instead of substrings

A: No, because when using substrings to build a re, there may be special characters, which may cause problems, as shown below

// Expect result: 'AhelloX hello3 '
> 'hello. helloX hello3 '.replace(new RegExp('hello. '.'g'), 'A')
< "AAA"
Copy the code

Replacing substrings in javascript can only be done in one clever way: str.split(‘foo’).join(‘bar’)

> 'hello. hello. hello. '.split('hello. ').join('A')
< "AAA"
Copy the code

Is really a clever (stupid) wonderful (clumsy) method !!!!! Perhaps TC39 also realized a problem, and a new API was created in ESNext

String.prototype.replaceAll()

'aabbcc'.replaceAll('b'.'. '); 
// 'aa.. cc'
Copy the code

Detailed documentation in the String. The prototype. ReplaceAll

Summary (and direct answers)

Two ways

  • str.split('foo').join('bar')
  • str.replaceAll('foo', 'bar')In theESNextMedium, the current support is not good

Pay attention to my

Scan code to add my wechat, remarks into the group, join the advanced front-end advanced group

Add me wechat to get you into the interview communication group

Welcome to pay attention to the public account [Internet Big factory recruitment], regularly push big factory internal promotion information and brief answers to interview questions, learn five minutes a day, half a year into the big factory

Five minutes a day, six months in dachang