Reputation: 47
I need a regex for removing specific consecutive characters.
For example. I can use
var filtered = oldString.replace(/[^[\w]\s]|(.)(?=\1)/gi, "");
If I need to get rid of any consecutive characters.
And I can use.
var filtered = oldString.replace(/[^[\w]\s]|(,|;|\s)(?=\1)/gi, "");
If I need to get rid of consecutive commas, semi-colons and space characters.
But what I exactly need is to make string like ;,
look like ;
.
And string like ,,,,, ;
look like single comma ,
.
So I need to get rid of any consecutive chars of some type.
How I am supposed to do that?
Upvotes: 2
Views: 648
Reputation: 4981
Based on your question, my understanding is that you want to replace a set of predefined characters occurring consecutively with the first occurring one. You can do this:
([;,])[;,]*(?:[;,\h]*[;,]+)?
,
, ;
and horizontal spaces \h
i.e single space or tab([;,])
(?:[;,\h]*[;,]+)?
is a non-capturing group which allows spaces in betweenReplace with $1
This will replace a combination of ,
, ;
and spaces \h
with the first one i.e
,,,,,,,,;
will get changed to ,
;;;;; , , , , ;, ;, ;
will get changed to ;
Upvotes: 0
Reputation: 626747
It seems you want to match chunks of the characters that are matched with the same pattern but keep the first matched char only. Use
.replace(/(\W)\W*/g, '$1')
See the regex demo
The pattern will match:
(\W)
- a non-word char (and capture into Group 1 so that the $1
backreference in the replacement pattern could restore this char)\W*
- 0+ non-word chars (they will be removed from the string)Note that this is a generic approach, and in most cases the pattern should be further adjusted.
Upvotes: 1