woopsie
woopsie

Reputation: 95

using regex with javascript and getting variables

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');

Upvotes: 2

Views: 87

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18641

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.

Upvotes: 1

Related Questions