简体   繁体   中英

remove second comma from a string in javascript

I have an string as:

0123456789,, 0987654213 ,, 0987334213,, ......

How can I convert this into

0123456789, 0987654213, 0987334213, ......

ie I want to remove the second comma

You can do it very simply, like this using regex.

var str = "0123456789,,0987654213,,0987334213,,,,,9874578";
str=str.replace(/,*,/g,',');
console.log(str)
var str = "0123456789,, 0987654213 ,, 0987334213,, ......"
console.log(str.replace(/\,+/g,","));

You can use replace() method with regular expression with g flag to replace all instances ',,' with ',':

str.replace(/,,/g, ",");

Here's a simple example

 var str = '0123456789,, 0987654213 ,, 0987334213'; str = str.replace(/,,/g, ","); console.log(str); 

这将用单个逗号替换所有出现的连续逗号:

str.replace(/,+/g, ',');

 var str = "0123456789,, 0987654213 ,, 0987334213,," str = str.split(",,").join(",") console.log(str); 

There is a replace method for String. You can replace ',,' with a ','.

An example:

var str = "0123456789,, 0987654213,, 0987334213,"; 
var newStr = str.replace(/,,/g,','));

The output:

0123456789, 0987654213, 0987334213,

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