javascript replace regex

2

I need to make a replace in a whole string with a format similar to the following:

var miRegExp = "^[0-9]+$";
var miString = $("input").val();
miString = miString.replace(new RegExp(miRegExp)+ /g, '');

The objective is to replace all the characters that are not supported in my string, in this case numbers, although I have other cases that I will use from this example to replace other patterns for chains such as mails, user names, etc.

The exposed example does not work and it throws an error but I put it so that it is understood what I want to achieve

    
asked by Pablo 11.05.2018 в 17:15
source

2 answers

2

Javascript has an explicit notation to create a RegExp, using / as a delimiter instead of quotes. After the closing delimiter you can add the flags, as you try. The other way is to use the constructor, which works in a more classic way:

let re1= new RegExp("[aeiou]","g");
//es equivalente a
let re2=/[aeiou]/g;

console.log("hola que tal".replace(re2,"!"))
console.log("hola que tal".replace(re1,"!"))
    
answered by 11.05.2018 в 17:22
1

You could also limit the entry of unwanted characters. Define the event oninput (for example) on the corresponding element when loading su DOM. For the case you have in hand (only numbers), the code can be similar to the following:

var edadInput = document.getElementById("edad");

edadInput.oninput = function(event) {
  edadInput.value = edadInput.value.replace(/[^\d]/g, "");
};
<input id="edad" placeholder="Edad" maxlength="3">
    
answered by 11.05.2018 в 19:06