2. Replace the blank space

Title description

Please implement a function to replace each space in a string with’ %20′. For example, when the string is We Are Happy, the replaced string is We%20Are%20Happy.

The topic is not very precise:

1. Can multiple spaces be allowed to appear continuously?

2. If it is possible to have multiple spaces in succession, replace them with multiple or single 20%?

There are three kinds of solutions

1. There will be no consecutive spaces:

The string is directly cut into arrays with spaces and connected with 20%.

function replaceSpace(str)
 {
 return str.split(' ').join('%20');
 }

2. Multiple spaces are allowed, and each space is replaced by a 20%:

Replace all spaces with regular expressions

function replaceSpace(str)
 {
 return str.replace(/\s/g,'%20');
 }

—–2019.1.8—– add

It is also possible to use the above split method here, for example

'a   b'.split(' ')

["a", "", "", "b"]

join

a%20%20%20b

—–2019.1.8—– add

3. Multiple spaces are allowed, and multiple spaces are replaced by one 20%.
Use regular expressions to find consecutive spaces to replace

function replaceSpace(str)
 {
 return str.replace(/\s+/g,'%20');
 }