Dưới đây là một thay thế JavaScript nhìn tích cực cho thấy cách lấy tên cuối cùng của những người có 'Michael' làm tên đầu tiên của họ.
1) Cho văn bản này:
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?";
có được một loạt tên cuối cùng của những người tên Michael. Kết quả sẽ là:["Jordan","Johnson","Green","Wood"]
2) Giải pháp:
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) Kiểm tra giải pháp
console.log(JSON.stringify( getMichaelLastName(exampleText) ));
// ["Jordan","Johnson","Green","Wood"]
Demo tại đây: http://codepen.io/PiotrBerebecki/pen/GjwRoo
Bạn cũng có thể dùng thử bằng cách chạy đoạn trích bên dưới.
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) ));