As far as I can tell, my RegEx is correct and the replace method should be doing it's thing. Looking at the answers here and here, it seems I am using the same, or a very very similar, RegEx pattern, and they are accepted answers.
So I'm thinking perhaps I'm doing something wrong with the .replace method?
Ideally, the RegEx should match anything not contained in the character class, meaning anything that is not: a-z, 0-9, '-', '.', and '_'. I read that there is no need to escape special characters within character classes (except '[', ']', and '-') so I have only escaped the hyphen.
Any help is much appreciated. To clarify; passing the below function this string:
'_;<!--Invalid--!"s"' null'
should return
____--invalid--____null
.
function nameSafe(name) {
var rgxIllegalChars = /^[^a-z0-9\-._]+$/;
name = name.toLowerCase();
return name.replace(rgxIllegalChars, '_');
}
Edit: Solved, see accepted answer for information. Finished function:
function nameSafe(name) {
var rgxIllegalChars = /[^a-z0-9\-._]+/gi;
return name.replace(rgxIllegalChars, '_');
}
I added some debugging output to my function to try and catch the before and after, and somewhat foolishly forgot that .replace doesn't actually replace the original string. So I was doing this:
console.log(name);
name.replace(rgxIllegalChars, '_');
console.log(name);
return name;
My apologies - if you're also having trouble, never forget to check your absolute basics (like I did) - does the method your using return a new object, or replace the existing one?