I’m trying to filter all of the non-alpha characters out of a string, giving me only a-z and A-Z as a result, but getting the regex to work inside JS has me scratching my head somewhat.
At the moment, I’ve got something along the following lines to test things out, where I’m trying to filter out all the spaces and number, giving me just the alphabet a-z.
var strInput = ' abc2defg6hijk8lmn4opq9rs tu0vw6xyz ';
var abc = strInput.trim().toLowerCase();
myRegex = /^[a-zA-Z]+$/;
strNew = myRegex.split(abc);
but that tells me that split() isn’t a function. Changing that last line to…
strNew = myRegex.exec(abc);
gives me an array containing only one character - “a”
You can achieve what you want by modifying the regex pattern slightly: /[a-zA-Z]+/g
By taking away the ^ and $ the pattern can now be matched regardless of where it starts or ends (so you don’t need to worry about trimming the string, for example). By adding the g flag after the pattern you’re specifying you want it to match all occurances, not just the first one it finds.
This’ll return you an array of each contiguous run of aphabetical characters.
var strInput = ' abC2dEfg6hijk8lmn4opq9rs tu0vw6xyz ';
var abc = strInput.toLowerCase();
var myRegex = /[a-zA-Z]+/g;
var strNew = myRegex.match(abc);
console.log(strNew);
only to get
Uncaught TypeError: myRegex.match is not a function at <anonymous>:4:22
EDIT: Forget that. Needed to rearrange line #4 as var strNew = abc.match(myRegex);
All is good, I worked that one out. I have just discovered that running .join('') on a null string doesn’t go down so well either. From MDN .join() description
The string conversions of all array elements are joined into one string. If an element is undefined or null, it is converted to the empty string.
I was just expecting an empty string based on that, but it didn’t like it.