Javascript regex to catch either ‘%20’ or whitespace

Can’t get my head around regex. Want to turn this string:

 var str = "Hello my%20name is%20Jascination"

into

 str2 = "Hello&my&name&is&Jascination"

I’ve tried:

 var str2 = str.replace(/[20%]/w/s/g, '&')
 var str2 = str.replace(/[20%/w/s]/g, '&')

but these don’t work. With Regex how do I capture both specific characters and specific groups of characters?

Answer

It’s easy. Just use or (x|y)

var str2 = str.replace(/%20| /g, '&');

Regular expression visualization

Debuggex Demo

Leave a Reply

Your email address will not be published. Required fields are marked *