You can use regex
myString.replace(/[^\w\s!?]/g,'');
This will replace everything but a word character, space, exclamation mark, or question.
Character Class:
\wstands for "word character", usually[A-Za-z0-9_]. Notice the inclusion of the underscore and digits.
\sstands for "whitespace character". It includes[ \t\r\n].
If you don't want the underscore, you can use just [A-Za-z0-9].
myString.replace(/[^A-Za-z0-9\s!?]/g,'');
For unicode characters, you can add something like \u0000-\u0080 to the expression. That will exclude all characters within that unicode range. You'll have to specify the range for the characters you don't want removed. You can see all the codes on Unicode Map. Just add in the characters you want kept or a range of characters.
For example:
myString.replace(/[^A-Za-z0-9\s!?\u0000-\u0080\u0082]/g,'');
This will allow all the previously mentioned characters, the range from \u0000-\u0080 and \u0082. It will remove \u0081.
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
You can use regex
myString.replace(/[^\w\s!?]/g,'');
This will replace everything but a word character, space, exclamation mark, or question.
Character Class:
\wstands for "word character", usually[A-Za-z0-9_]. Notice the inclusion of the underscore and digits.
\sstands for "whitespace character". It includes[ \t\r\n].
If you don't want the underscore, you can use just [A-Za-z0-9].
myString.replace(/[^A-Za-z0-9\s!?]/g,'');
For unicode characters, you can add something like \u0000-\u0080 to the expression. That will exclude all characters within that unicode range. You'll have to specify the range for the characters you don't want removed. You can see all the codes on Unicode Map. Just add in the characters you want kept or a range of characters.
For example:
myString.replace(/[^A-Za-z0-9\s!?\u0000-\u0080\u0082]/g,'');
This will allow all the previously mentioned characters, the range from \u0000-\u0080 and \u0082. It will remove \u0081.
Both answers posted so far left out the question mark. I would comment on them, but don't have enough rep yet.
David is correct, sachleen's regex will leave underscores behind. rcdmk's regex, modified as follows, will do the trick, although if you care about international characters things might get a lot more complicated.
var result = text.replace(/[^a-zA-Z0-9\s!?]+/g, '');
This will leave behind new lines and tabs as well as spaces. If you want to get rid of new lines and tabs as well, change it to:
var result = text.replace(/[^a-zA-Z0-9 !?]+/g, '');
javascript - Regex: remove everything except the letters and separator - Stack Overflow
What is the regex pattern to remove all characters except numbers and letters?
javascript - Regular expression to remove anything but alphabets and '[single quote] - Stack Overflow
javascript - Regex to remove letters, symbols except numbers - Stack Overflow
A carefully chosen regular expression can strip out the weightings in one replacement. A second switches the hyphens - for underscores _
const locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5';
newLocales = locales.replace(/;q=\d*\.\d*/g,'').replace(/-/g,'_');
console.log(newLocales); // fr_CH, fr, en, de, *
You could replace and search for two small characters and possible following dash and some more upper case characters or a star.
const
locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5',
parts = locales
.replace(/-/g, '_')
.match(/[a-z]{2}_*[A-Z]*|\*/g)
.join(', ');
console.log(parts);
An even shorter approach which relaces all parts after semicolon (inclusive) until following comma without converting/matching to an array an joining back to a string.
const
locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5',
parts = locales
.replace(/-/g, '_')
.replace(/;[^,]+/g, '')
console.log(parts);
Add the global option at the end of the regex - see demo below:
console.log("AkjkljKK".replace(/(?![A-Z])./g, ''));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
you can use [^A-Z] to remove everything except capital letters. Also use g to replace all occurrences and not just the first one.
var str = "sOmeVALUE";
console.log(str.replace(/[^A-Z]/g, ""));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Use negated character set:
If you're okay keeping the underscore, you can use:
str.replace(/[^\w]/g, "-") // \w is the same as [A-Za-z0-9_]
If you want to replace that as well, then you can use:
str.replace(/[^A-Za-z0-9]/g, "-")
Edit: As mentioned by @JamesBuck, there are actually negated shorthands: [^\w] is the same as \W, so if you don't need to replace the underscore, you can use that, resulting in:
str.replace(/\W/g, "-")
var str = "djdkasfh da@S@FA";
str.replace(/[^a-z0-9]+/gi, '-');
Outputs djdkasfh-da-S-FA.
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'.
As @chris85 said, you can use the regular expression [^0-9a-z-A-Z] to replace all the characters that are not letters, numbers, or whitespace.
Here is a function that will do what you want:
function clean(str) {
return str.replace(/[^0-9a-z-A-Z ]/g, "").replace(/ +/, " ")
}
The second replace call is needed to remove the runs of extra whitespace that are made from removing a character that is between spaces.
Use replace
string.replace(/[^A-Z\d\s]/gi, '')
Note the two flags at the end of the regex
g - stands for global, and means that every such instance of the regular expression will be found
i - stands for case insensitive. That means it will match both lower case and uppercase characters
Playing with your string, it returns this output
"Players got to play justsaying"
To transform two or more whitespace characters into a single whitespace, you could hain another replace method to the existing ones.
string.replace(/[^A-Z\d\s]/gi, '').replace(/\s+/g, ' ')
The key here is the + character, which finds one or more.
It's probably possible to do it more efficiently, but I'm an amateur in Regex.