简体   繁体   中英

how to replace a string which is not integer using regex in javascript

i have use this regex try to replace a string which is not a integer ,however it replace when it is a integer.

 this.v=function(){this.value=this.value.replace(/^(-?[1-9]\d*|0)$/,'');}

what is the opposite regex? :what is the regex for replace a string which is not a integer with "".

eg:if user entered string is not -2,0,1,123 such like that i want clear the input.if string like 2e3r,2.5,-1.3 the input will be clear value

You could sanitize user input using parseInt or Number methods. For example:

    var normalInput = "1";
    normalInput = parseInt(normalInput, 10);
    console.log(normalInput); // prints 1

    var wrongInput = "12a23-24";
    wrongInput = parseInt(wrongInput, 10);
    console.log(wrongInput); // prints 12 (stops after first not valid number)

Or something like that:

var myInput = "21312312321",
        processedInput = Number(myInput);

if(processedInput !== NaN){ // if number given is a valid number return it (also works for float input)
    console.log(processedInput);
    return processedInput;
}
else{ // otherwise return an empty string
    return "";
}

Jsfiddle example1 example2 .

If you must use regex then the following should work. Not tested for efficiency, just thrown together.

var numbersOnly = function(number_string) {
    var re = /(\+?|\-?)([0-9]+)(\.[0-9]+)*/g;
    return number_string.match(re);
}

numbersOnly('pears1.3apples3.2chinesefood-7.8');
// [ '1.3', '3.2', '-7.8' ]

我已经通过更改函数逻辑解决了这一问题:

onblur="(this.v=function(){var re=/^(-?[1-9]\d*|0)$/;if(!re.test(this.value)){this.value=''}}).call(this)

要删除字符串中的所有非数字字符:

this.v=function(){this.value=this.value.replace(/\D+/g,'');}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM