How can I remove all characters from a string that are not letters using a JavaScript RegEx?
RegEx instance properties used g , i
global : Whether to test the regular expression against all possible matches in a string, or only against the first.
ignoreCase : Whether to ignore case while attempting a match in a string.
RegEx special characters used [a-z] , +
[^xyz] : A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen.
For example,
[abcd]is the same as[a-d]. They match the 'b' in "brisket" and the 'c' in "chop".+ : Matches the preceding item 1 or more times. Equivalent to {1,}.
JavaScript string replace method syntax
str.replace(regexp|substr, newSubStr|function[, Non-standard flags]);
The non-standard flags g & i can be passed in the replace syntax or built into the regex.
examples:
var re = /[^a-z]+/gi; var str = "this is a string"; var newstr = str.replace(re, ""); print(newstr);
var str = "this is a string"; var newstr = str.replace(/[^a-z]+/, "", "gi"); print(newstr);
To match whitespace characters as well \s would be added to the regex [^a-z\s]+.
JavaScript Reference