I want to replace all the characters of the input type text, I have seen on the internet that /g is used, but when I put it, I get an error that it is not "defined"
function replaceAllInvalidCharacter(id){
var characters = ["/","\\", "¿","?","#","<",">","[","]","{","}","%","="];
var val = document.getElementById(id).value;
for(var i = 0 ; i < characters.length; i++){
if (val.indexOf(characters[i]) != -1) {
val = val.replace(characters[i]/g, '');
}
}
document.getElementById(id).value = val;
}
bug ->
Uncaught ReferenceError: g is not defined
How do I make it take all the characters?
For example: e/d/um/o/l/ay stay with edu cool...
Trying to concatenate
/g
there is pointless, as it can only be used with RegExp literals. Therefore you have two options:Examples:
As you can see, working with literals is more comfortable (you don't need the double
\
to escape characters), but in any case you won't be able to use indexof to search first, although it's not necessary.I think that what you want to do is done with a Regex (Regular Expression) and for what you put it would be the following
[/"\\¿?#<>\[\]{}%=]+
, being as follows:It would be enough to go through the collection of invalid characters in an array.map and replace them with ''
The problem is that the /g you are trying to use is from a regular expression, but the character value is not.
To fix it, you have to instantiate a regular expression. Use the following code:
For more documentation about regular expressions, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp