5

I am new to javascript, How to extract substring that matches a regex in a string in javascript?

For example in python:

version_regex =  re.compile(r'(\d+)\.(\d+)\.(\d+)')
line = "[2021-05-29] Version 2.24.9"
found = version_regex.search(line)
if found:
  found.group() // It will give the substring that macth with regex in this case 2.24.9

I tried these in javascript:

let re = new RegExp('^(\d+)\.(\d+)\.(\d+)$');
let x = line.match(re);

but I am not getting the version here.

Thanks in advance.

2
  • Don't use new RegExp if you're not constructing the regexp dynamically. Use a RegExp literal. Commented Aug 22, 2021 at 6:06
  • 1
    The reason it's not working is because you need to escape the backslashes in the string. You wouldn't have that problem if you used a literal. Commented Aug 22, 2021 at 6:07

1 Answer 1

10

You can use RegExp.prototype.exec which returns an Array with the full match and the capturing groups matches:

const input = '[2021-05-29] Version 2.24.9';

const regex = /(\d+)\.(\d+)\.(\d+)/;

let x = regex.exec(input);

console.log(x);

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

Comments

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.