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 ?
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 stringGlobal pattern flags
g modifier
: global. All matches (don't return after first match)
var string = ",,,a,,,,,b,,c,,,,d,,,,";
console.log(string.replace(/^,*|,+(?=,|$)/g, ''));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With