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

3
  • 2
    What happened when you tried to replace all ",," instances with ","? Surely you looked into string.replace methods? Commented Jun 20, 2017 at 9:47
  • 1
    Possible duplicate of How to replace all occurrences of a string in JavaScript? Commented Jun 20, 2017 at 9: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? Commented Jun 20, 2017 at 9:51

6 Answers 6

3

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

var str = "0123456789,,0987654213,,0987334213,,,,,9874578";
str=str.replace(/,*,/g,',');
console.log(str)
Sign up to request clarification or add additional context in comments.

2 Comments

@enhzflep Thanks.
Thank for your answer But the best Pattern for this goal is : replace(/,*,/g,','); ===> replace(/,+/g,',');
1
var str = "0123456789,, 0987654213 ,, 0987334213,, ......"
console.log(str.replace(/\,+/g,","));

3 Comments

That will reduce any sequence of two or more commas to one. Which isn't quite the requirement...
Isn't it incorrect? It will replace the first occurrence of ,, in str
The code is updated the above comment is no longer valid.
0

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

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

Comments

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

Comments

0

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

Comments

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,

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.