Bilal075_ Bilal075_ - 3 months ago 7
Javascript Question

JavaScript - making my regular expression work

So I have these 2 expressions:

1: [^a-zA-Z0-9]

2: [^a-zA-Z]


The first one must be used whenever my string starts with data- and the second one if it doesn't. However, I need this built-in into my regular expression (so using .slice(0, 5) == "data-" is no option for this situation).

Is it possible to do this inlined (so by just having to use 1 regular expression)? Or do I first have to validate (if string starts with data-) and then use the correct expression?

Thanks in advanced.

Some examples:

data-attribute@!#!19 => data-attribute19
data-attribute17 => data-attribute17
attribute19 => attribute
attribute1@!#!@#183 => attribute

Answer

You can do something a bit like this:

/^(data-[a-zA-Z0-9]+).+?(\d*)$|^([a-zA-Z]+).+$/

Which will match what you want, and then return the results inside either one or two capture groups (depending on which option it matches).

Breaking it Down

Going from left to right:

The ^ character means "beginning of line" - in this case, the beginning of a single string.

The parentheses () indicate a capture group - some substring that you want to capture and output separately from your main match string.

data- indicates the literal string "data-", with the hyphen at the end.

[a-zA-Z0-9]+ is a character class, repeated one or more times.

.+? is one or more of any characters, matched lazily - meaning it will "give up" some of its match to enable the next token to match as much as possible.

\d* means zero or more digits (equivalent to [0-9]*).

The $ character means "match the end of the line" (again, in this case, the end of your string).

The | character means "alternate" - basically, it will match either the pattern on the left or the pattern on the right, enabling this single regex to match either of your two strings.