Reputation: 383
I want to replace dot (.) in a string with empty string like this:
1.234 => 1234 However following regex makes it totally empty.
let x = "1.234";
let y = x.replace(/./g , "");
console.log(y);
However it works good when I replace comma (,) like this:
let p=x.replace(/,/g , "");
What's wrong here in first case i.e. replacing dot(.) by empty string? How it can be fixed?
I am using this in angular.
Upvotes: 0
Views: 1834
Reputation:
Use /[.]/g
instead of simply /./g
as .
matches almost any character
except whitespaces
console.log('3.14'.replace(/[.]/g, '')); // logs 314
Upvotes: 1
Reputation: 50291
An alternative way to do this(another post have already answered it with regex) is to use split
which will create an array and then use join
to join the elements of the array
let x = "1.234";
// splitting by dot(.) delimiter
// this will create an array of ["1","234"]
let y = x.split('.').join(''); // join will join the elements of the array
console.log(y)
Upvotes: 0
Reputation: 10682
Try this:
let x: string = "1.234";
let y = x.replace(/\./g , "");
Dot .
is a special character in Regex. If you need to replace the dot itself, you need to escape it by adding a backslash before it: \.
Read more about Regex special characters here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Upvotes: 4