Given the following string:
JavaScript
x
2
1
const myString = "This is my comment content. [~firstName.lastName]";
2
What is a javascript regex to extract the “firstName” and “lastName”?
What is a javascript regex to extract the content minus the “[~firstName.lastName]”?
I’m rubbish with Regex.
Advertisement
Answer
You could target each name separately. match
will return the complete match as the first element of the array, and the groupings specified by the (
and )
in the regex as the subsequent elements.
JavaScript
1
3
1
const str = 'This is my comment content. [~firstName.lastName]';
2
const regex = /[~(.+).(.+)]/;
3
console.log(str.match(regex));
Or you could target just the characters within the brackets and then split
on the .
.
JavaScript
1
3
1
const str = 'This is my comment content. [~firstName.lastName]';
2
const regex = /[~(.+)]/;
3
console.log(str.match(regex)[1].split('.'));