Regex to remove all non-alphanumeric and replace spaces +

I want to use regex to try to remove all non-alphabetic characters from a string and replace spaces with +

All I want to resolve is basically the alphabetical words AZ and +

This is specifically to prepare a string to become part of the URL, so instead of spaces you need + characters.

I looked at /\W+/ , however this removes all spaces and alphanumeric characters, whereas I want to leave spaces if possible, then replace with + characters.

I searched around a bit, but I can’t find something, I was hoping that someone might have some simple suggestions for this.

Example string and desired result: Durarara!!x2 Ten β†’ durarara + x2 + ten

+6
source share
2 answers

It is actually quite simple.

Assuming str is the line you clear:

 str = str.replace(/[^a-z0-9+]+/gi, '+'); 

^ means "nothing in this list of characters." + after the group [...] means "one or more". /gi means "replace whatever you find, regardless of case."

Thus, any number of characters that are not letters, numbers or "+" is converted to one "+".

To remove the substrings in brackets (as indicated in the comments), do this replacement first:

 str = str.replace(/\(.+?\)/g, ''); 

 function replacer() { var str = document.getElementById('before').value. replace(/\(.+?\)/g, ''). replace(/[^a-z0-9+]+/gi, '+'); document.getElementById('after').value = str; } document.getElementById('replacem').onclick = replacer; 
 <p>Before: <input id="before" value="Durarara!!x2 Ten" /> </p> <p> <input type="button" value="replace" id="replacem" /> </p> <p>After: <input id="after" value="" readonly /> </p> 
+22
source
  str = str.replace(/\s+/g, '+'); str = str.replace(/[^a-zA-Z0-9+]/g, ""); 
  • The first line replaces all spaces with the +
  • The second line deletes all characters other than alphanumeric, not "+".
0
source

All Articles