Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge contiguous "," into a single "," and remove leading and trailing "," in one RegExp

Suppose I have a string

",,,a,,,,,b,,c,,,,d,,,,"

I want to convert this into

"a,b,c,d"

in 1 RegExp operation.

I can do it in 2 RegExp operations like

var str = ",,,a,,,b,,,,c,,,,,,,,d,,,,,,";
str = str.replace(/,+,/g,",").replace(/^,*|,*$/g, '');

is it possible to do this in 1 RegExp operation ?

like image 652
marvel308 Avatar asked Jan 05 '17 20:01

marvel308


Video Answer


2 Answers

You could use a regular expression, which are at start or are followed by a comma or at the and and replace it with an empty string.

/^,*|,(?=,|$)/g

  • 1st Alternative ^,*

    ^ asserts position at start of the string

    • ,* matches the character , literally (case sensitive)

      * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

  • 2nd Alternative ,+(?=,|$)

    • ,+ matches the character , literally (case sensitive)

      + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

    • Positive Lookahead (?=,|$)

      Assert that the Regex below matches

      • 1st Alternative ,

        , matches the character , literally (case sensitive)

      • 2nd Alternative $

        $ asserts position at the end of the string

  • Global pattern flags

    g modifier: global. All matches (don't return after first match)

var string =  ",,,a,,,,,b,,c,,,,d,,,,";

console.log(string.replace(/^,*|,+(?=,|$)/g, ''));
like image 127
Nina Scholz Avatar answered Oct 04 '22 04:10

Nina Scholz


The approach below returns expected result using two processes. .match() and template literal, which casts the encapsulated javascript expression to string when assigned to a variable.

You can use String.prototype.match() with RegExp /[^,]+/ to negate matching comma character ,, match one or more characters other than ,, including + in RegExp following character class where , is negated to match "abc" as suggested by @4castle; template literal to cast resulting array to string.

var str = ",,,a,,,b,,,,c,,,,,,,,d,,,efg,,,";

str = `${str.match(/[^,]+/g)}`;

console.log(str);
like image 28
guest271314 Avatar answered Oct 04 '22 03:10

guest271314