First of all this question is not same as
strip non-numeric characters from string or
Regex to replace everything except numbers and a decimal point
I want to convert a string with valid number like.
--1234// will be -1234
-123-123 will be -123123
12.123.3 will be 12.1233
-123.13.123 will be -123.13123
I tried those
number.replace(/[^0-9.-]/g, '') //it accepts multiple . and -
number.replace(/[^0-9.]-/g, '').replace(/(\..*)\./g, '$1');//it accepts multiple minus
I am facing Problem with leading minus sign.
How I can convert a string which will remove all characters except leading -(remove other minus),digits and only one dot(remove other dots)
To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.
The RegExp [0-9] Expression in JavaScript is used to search any digit which is between the brackets. The character inside the brackets can be a single digit or a span of digits.
Using Python regex() “Regular Expressions” and sub() “Sub-string” Here we are using regx() “Regular Expression” to create a search pattern for space, and with the help of this search pattern, we are replacing the unwanted character from string with blank character by using sub() function.
Here I am sharing my solution.
Lets assume the string is a
;
//this will convert a to positive integer number
b=a.replace(/[^0-9]/g, '');
//this will convert a to integer number(positive and negative)
b=a.replace(/[^0-9-]/g, '').replace(/(?!^)-/g, '');
//this will convert a to positive float number
b=a.replace(/[^0-9.]/g, '').replace(/(..*)./g, '$1');
//this will convert a to float number (positive and negative)
b=a.replace(/[^0-9.-]/g, '').replace(/(..*)./g, '$1').replace(/(?!^)-/g, '');
//For positive float number
b=a.replace(/[^0-9.]/g, '').replace('.', 'x').replace(/\./g,'').replace('x','.');
//For Negative float number
b=a.replace(/[^0-9.-]/g, '').replace('.', 'x').replace(/\./g,'').replace('x','.').replace(/(?!^)-/g, '');
Based on @Shaiful Islam's answer, I added one more code.
var value = number
.replace(/[^0-9.-]/g, '') // remove chars except number, hyphen, point.
.replace(/(\..*)\./g, '$1') // remove multiple points.
.replace(/(?!^)-/g, '') // remove middle hyphen.
.replace(/^0+(\d)/gm, '$1'); // remove multiple leading zeros. <-- I added this.
Result
00.434 => 0.434
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With