2

I've not used regex in a while and I'm trying to use it in Javascript

I have a url string like /something/a/a123 and I only want to match strings that begin with /something and be able to get a and a123 as variables without splitting the string into an array.

Is that possible?

const r = /something/[a-z][A-Z]*/[a-z0-9][a-z0-0]*/
const s = r.exec('/something/a/a123');

1 Answer 1

1

Use

const r = /something\/([a-z]+)\/([a-z0-9]+)/i
const [_, a, b] = r.exec('/something/') || [,'','']
console.log(a, b)

Escape slashes and use round parens to capture those necessary regex parts.

Sign up to request clarification or add additional context in comments.

5 Comments

... for the sake of not failing due to null es possible return value for exec you might consider changing your 2nd line to const [_, a, b] = r.exec('/something/a/a123') || [];
how can I exclude a particular word? eg. I want /something/a/a123 but I don't want /something/a/specificNonAlphaWord
@woopsie /something\/([a-z]+)\/(?!word)([a-z0-9]+)/i
is there a way to make it ONLY accept alphanums wihtout having to use (?!word)? \/([a-z0-9]+) something here to make sure it's only alpha? /i
@woopsie /something\/([a-z]+)\/((?:[a-z]+\d|\d+[a-z])[\da-z]*)/i might do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.