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

Question

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

Answers 2
Added at 2017-01-05 21:01
Tags
Question

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 ?

Answers to

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

nr: #1 dodano: 2017-01-05 21:01

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

nr: #2 dodano: 2017-01-05 21:01

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

Source Show
◀ Wstecz