Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove all non alpha-numeric and replace spaces with +

I'm looking to use regex to try remove all non alpha-numeric characters from a string and replace spaces with a +

All I want to permit is basically alphabetical words A-Z and +

This is specifically to prepare the string to become a part of a URL, thus need the + symbols instead of spaces.

I have looked at /\W+/ however this removes all white spaces and alpha-numeric characters, whereas I want to leave the spaces in if possible to then be replaced by + symbols.

I've searched around a bit but I can't seem to find something, I was hoping someone might have any simple suggestions for this.

Sample string & Desired result: Durarara!!x2 Ten -> durarara+x2+ten

like image 296
sgript Avatar asked Aug 19 '15 21:08

sgript


People also ask

How do I remove all non-alphanumeric characters from a string?

To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.

How do you replace all non-alphanumeric character with empty string provide answer using regex?

replaceAll("/[^A-Za-z0-9 ]/", ""); java. regex.

How do you match only alphanumeric in regular expressions?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.


2 Answers

This is actually fairly straightforward.

Assuming str is the string you're cleaning up:

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

The ^ means "anything not in this list of characters". The + after the [...] group means "one or more". /gi means "replace all of these that you find, without regard to case".

So any stretch of characters that are not letters, numbers, or '+' will be converted into a single '+'.

To remove parenthesized substrings (as requested 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>
like image 175
Paul Roub Avatar answered Sep 20 '22 08:09

Paul Roub


 str = str.replace(/\s+/g, '+');
 str  = str.replace(/[^a-zA-Z0-9+]/g, "");
  • First line replaces all the spaces with + symbol
  • Second line removes all the non-alphanumeric and non '+' symbols.
like image 22
Praveen reddy Dandu Avatar answered Sep 19 '22 08:09

Praveen reddy Dandu