Be aware, that \W leaves the underscore. A short equivalent for [^a-zA-Z0-9] would be [\W_]
text.replace(/[\W_]+/g," ");
\W is the negation of shorthand \w for [A-Za-z0-9_] word characters (including the underscore)
Example at regex101.com
Answer from Jonny 5 on Stack OverflowBe aware, that \W leaves the underscore. A short equivalent for [^a-zA-Z0-9] would be [\W_]
text.replace(/[\W_]+/g," ");
\W is the negation of shorthand \w for [A-Za-z0-9_] word characters (including the underscore)
Example at regex101.com
Jonny 5 beat me to it. I was going to suggest using the \W+ without the \s as in text.replace(/\W+/g, " "). This covers white space as well.
removing all non-letter characters from a string? ((using regex))
javascript - Regex to remove all non alpha-numeric and replace spaces with + - Stack Overflow
regex - Remove all non alphanumeric and any white spaces in string using javascript - Stack Overflow
Spinal case, regex
I am currently trying this two different ways and they aren't working - I'm checking the input value and running this every time a key is pressed:
input.replace(/[^a-zA-z]/, "");
and
for(var i = 0; i < input.length; i++){
if( input[i] == /[^a-zA-z]/g){
console.log("input " + input[i] + " is not a letter!");
input.replace(input[i], "");
}
}jsfiddle here
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, "");
- First line replaces all the spaces with + symbol
- Second line removes all the non-alphanumeric and non '+' symbols.
Removing non-alphanumeric chars
The following is the/a correct regex to strip non-alphanumeric chars from an input string:
input.replace(/\W/g, '')
Note that \W is the equivalent of [^0-9a-zA-Z_] - it includes the underscore character. To also remove underscores use e.g.:
input.replace(/[^0-9a-z]/gi, '')
The input is malformed
Since the test string contains various escaped chars, which are not alphanumeric, it will remove them.
A backslash in the string needs escaping if it's to be taken literally:
"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')
"testredbobfrednew" // output
Handling malformed strings
If you're not able to escape the input string correctly (why not?), or it's coming from some kind of untrusted/misconfigured source - you can do something like this:
JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')
"testredbobfrednew" // output
Note that the json representation of a string includes the quotes:
JSON.stringify("\\test\red\bob\fred\new")
""\\test\red\bob\fred\new""
But they are also removed by the replacement regex.
All of the current answers still have quirks, the best thing I could come up with was:
string.replace(/[^A-Za-z0-9]/g, '');
Here's an example that captures every key I could find on the keyboard:
var string = '123abcABC-_*(!@#$%^&*()_-={}[]:\"<>,.?/~`';
var stripped = string.replace(/[^A-Za-z0-9]/g, '');
console.log(stripped);
Outputs: '123abcABC'.
You're using toLowerCase when creating strReverse, and then comparing it with str. But str will still have upper-case characters in it. Additionally, you're leaving the non-alpha characters in str.
You also need to remove _ for the last one to work, which \W won't do on its own.
You need to first prep str, then create the reversed version of it, and do the check:
function palindrome(str) {
var strReverse;
str = str.toLowerCase().replace(/\W|_+/g,'');
strReverse = str.split('').reverse().join('');
return strReverse === str;
}
Live Example:
function palindrome(str) {
var strReverse;
str = str.toLowerCase().replace(/\W|_+/g,'');
strReverse = str.split('').reverse().join('');
return strReverse === str;
}
function test(str, expectedResult) {
var result = palindrome(str);
var p = document.createElement('p');
p.className = !result == !expectedResult ? "good" : "bad";
p.appendChild(document.createTextNode(str));
document.body.appendChild(p);
}
test("eye", true);
test("race car", true);
test("not a palindrome", false);
test("A man, a plan, a canal. Panama", true);
test("never odd or even", true);
test("nope", false);
test("almostomla", false);
test("My age is 0, 0 si ega ym.", true);
test("1 eye for of 1 eye.", false);
test("0_0 (: /-\ :) 0-0", true);
.good {
color: green;
}
.bad {
color: #d00;
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Try this function
function palindrome(str) {
str=str.toLowerCase().replace(/[^A-Za-z]+/g, '');
var strReverse = str.split('').reverse().join('');
if(strReverse===str)
return true;
else
return false;
}
Issue in your code was that when you were comparing the strReverse with str, strReverse was formatted but str was not. Like you didn't remove special characters and spaces and numbers from str, you didn't made it lowercase etc.
Check this fiddle for every test case
this.colorPreset1=this.colorPreset1.replace(/[^0-9a-zA-Z]/g, '');
The character group was changed to a exclusion group. [^] will match any character not in the list. As you had it, it would only match the characters you wanted to keep.
The anchors for the string were removed - You're wanting to replace any non-alpha numeric characters, so it doesn't matter where they're located.
The global flag //g was added so it will replace all matches instead of just the first one.
By adding ^ and $ around your regular expression, you explicitly tell it to match strings starting and ending with this pattern.
So it will replace the searched pattern only if if all the content of the string matches the pattern.
If you want to match each occurence of non numerical or alphabetical characters, you will have to remove the ^ start constraint and the $ end constraint, but also will have to change the pattern itself:
[A-Za-z0-9]
matches alphabetical or numerical characters, you want the opposite of that (to inverse a character class add a ^ at the start of the character class:
[^A-Za-z0-9]
finally add the g option to the regex to tell it to match each occurence (otherwise only the first occurence will be replaced):
/[^A-Za-z0-9]+/g
If you want to match ")" and "-" separately, use g flag
"File name) - Title".match(/[^ a-zA-Z\d\s:]/g)
If you want to match ") -" which is non-alphanumeric+space+non-alphanumeric,
"File name) - Title".match(/^ a-zA-Z\d\s:*[^ a-zA-Z\d\s:]/g)
/\s*(?:[^a-zA-Z\d\s:]\s*)+/
This regular expression matches optional leading spaces that are followed by one or more groups of non alphanumeric characters and optional trailing spaces. The question mark just means that what is captured within the round brackets is not saved as special component