Below is a positive lookbehind JavaScript alternative showing how to capture the last name of people with 'Michael' as their first name.
1) Given this text:
const exampleText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";
get an array of last names of people named Michael.
The result should be: ["Jordan","Johnson","Green","Wood"]
2) Solution:
function getMichaelLastName2(text) {
return text
.match(/(?:Michael )([A-Z][a-z]+)/g)
.map(person => person.slice(person.indexOf(' ')+1));
}
// or even
.map(person => person.slice(8)); // since we know the length of "Michael "
3) Check solution
console.log(JSON.stringify( getMichaelLastName(exampleText) ));
// ["Jordan","Johnson","Green","Wood"]
Demo here: http://codepen.io/PiotrBerebecki/pen/GjwRoo
You can also try it out by running the snippet below.
const inputText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";
function getMichaelLastName(text) {
return text
.match(/(?:Michael )([A-Z][a-z]+)/g)
.map(person => person.slice(8));
}
console.log(JSON.stringify( getMichaelLastName(inputText) ));
0
Created by Piotr Berebecki on 2020-03-10 16:16:13 +0000 UTC
Share