Di bawah ini adalah tampilan positif di balik alternatif JavaScript yang menunjukkan cara menangkap nama belakang orang dengan 'Michael' sebagai nama depan mereka.
1) Diberikan teks ini:
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?";
dapatkan berbagai nama belakang orang yang bernama Michael. Hasilnya harus:["Jordan","Johnson","Green","Wood"]
2) Solusi:
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) Periksa solusinya
console.log(JSON.stringify( getMichaelLastName(exampleText) ));
// ["Jordan","Johnson","Green","Wood"]
Demo di sini: http://codepen.io/PiotrBerebecki/pen/GjwRoo
Anda juga dapat mencobanya dengan menjalankan cuplikan di bawah ini.
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) ));