0

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.

1
  • 2
    You need to escape special characters in regular expressions. Commented May 22, 2018 at 2:39

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

You probably should add that . is the wildcard character that matches one of anything.
1

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

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.