User 101
User 101

Reputation: 1431

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, ......

i.e I want to remove the second comma

Upvotes: 0

Views: 1816

Answers (6)

Man Programmer
Man Programmer

Reputation: 5356

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

Upvotes: 1

Simone Boccato
Simone Boccato

Reputation: 189

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,

Upvotes: 0

Farhad Azarbarzinniaz
Farhad Azarbarzinniaz

Reputation: 739

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

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

Upvotes: 3

Hassan Imam
Hassan Imam

Reputation: 22534

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

Upvotes: 0

Raj
Raj

Reputation: 2028

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

Upvotes: 0

Lennholm
Lennholm

Reputation: 7470

This will replace all occurrences of consecutive commas with a single comma:

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

Upvotes: 0

Related Questions