简体   繁体   中英

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

在此处输入图片说明

However it works good when I replace comma (,) like this:

 let p=x.replace(/,/g , "");

What's wrong here in first case ie replacing dot(.) by empty string? How it can be fixed?

I am using this in angular.

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

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

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

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM