0

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

User 101
  • 1,351
  • 3
  • 12
  • 18
  • 2
    What happened when you tried to replace all ",," instances with ","? Surely you looked into string.replace methods? – enhzflep Jun 20 '17 at 09:47
  • 1
    Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Jaydeep Mor Jun 20 '17 at 09:49
  • 1
    The second pair of commas is proceeded by a space in the input; that space is not in the output: typo or part of the problem? – Richard Jun 20 '17 at 09:51

6 Answers6

3

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

var str = "0123456789,,0987654213,,0987334213,,,,,9874578";
str=str.replace(/,*,/g,',');
console.log(str)
enhzflep
  • 12,927
  • 2
  • 32
  • 51
1
var str = "0123456789,, 0987654213 ,, 0987334213,, ......"
console.log(str.replace(/\,+/g,","));
Man Programmer
  • 5,300
  • 2
  • 21
  • 21
0

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);
Raj
  • 1,928
  • 3
  • 29
  • 53
0

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

str.replace(/,+/g, ',');
Lennholm
  • 7,205
  • 1
  • 21
  • 30
0

var str = "0123456789,, 0987654213 ,, 0987334213,,"
str = str.split(",,").join(",")
console.log(str);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

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,
Simone Boccato
  • 199
  • 1
  • 14