Skip to content
Advertisement

Regex to extract text from a string

Given the following string:

const myString = "This is my comment content. [~firstName.lastName]";

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.

const str = 'This is my comment content. [~firstName.lastName]';
const regex = /[~(.+).(.+)]/;
console.log(str.match(regex));

Or you could target just the characters within the brackets and then split on the ..

const str = 'This is my comment content. [~firstName.lastName]';
const regex = /[~(.+)]/;
console.log(str.match(regex)[1].split('.'));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement