Hi Friends 👋,
Welcome To Infinitbility! ❤️
To remove special characters and space from number in javascript, just use replace()
method with /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g
regex then it will return new string without special characters and spaces then convert it number.
The replace()
method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
Let’s take an example to remove special characters and space using replace()
method.
const regex = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g;
var str = "12 3&&9 04";
// + unary plus oprator it's the fastest way to convert a string to a number
+str.replace(regex, '');
// 👇️ Output
// 123904
Today, I’m going to show you How do I remove special characters and spaces from numbers in javascript, as above mentioned here, I’m going to use the replace()
method with /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g
regex to delete special characters and space from a string and then convert it to number.
Let’s start today’s tutorial how do you remove special characters and space from numbers in javascript?
In this example, we will do
- take sample number string variable
- remove special characters and space
- convert it to a number
Let’s write code…
javascript replace example
const regex = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g;
// take sample number string variable
let num = "235 && 243";
// remove special characters and space
num = num.replace(regex, '');
// convert it to number
num = +num;
console.log(num)
As mentioned above, we are taken the example of a number string variable, remove special characters and spaces from the string, converted the string to a number, and print the output on the screen.
I hope it helps you, All the best 👍.