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
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.
replaceAll("/[^A-Za-z0-9 ]/", ""); java. regex.
The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.
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>
str = str.replace(/\s+/g, '+');
str = str.replace(/[^a-zA-Z0-9+]/g, "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With