Gautam
Gautam

Reputation: 383

How to replace '.' with empty string

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);

enter image description here

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

Answers (3)

user9090230
user9090230

Reputation:

Use /[.]/g instead of simply /./g as . matches almost any character except whitespaces

console.log('3.14'.replace(/[.]/g, '')); // logs 314

Upvotes: 1

brk
brk

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

Arash Motamedi
Arash Motamedi

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

Related Questions