Skip to content Skip to sidebar Skip to footer

Capture Word Before A Specific Character

I need to create a javascript regular expression that will capture the 'word' that comes before a single or double :. Here are some examples: *, ::before, ::after // do not capture

Solution 1:

You can use this regex:

 ([.\w]+):?:\w+

Working demo

enter image description here

As you need, this regex does:

([.\w]+)      Captures alphanumeric and dots strings before
:?:\w+oneor two colons followed withsome alphanumeric

Match information:

MATCH 1
1.  [57-64] `.class2`
MATCH 2
1.  [72-79] `.class3`
MATCH 3
1.  [119-126]   `.class4`

Solution 2:

Simply add on an additional/optional : to the end:

/(\S+?)::?/g

Or you can specify this as a repetition 1-2 times:

/(\S+?):{1,2}/g

Demo

Post a Comment for "Capture Word Before A Specific Character"