javascript regex - look behind alternative?

前端 未结 6 1985
时光取名叫无心
时光取名叫无心 2020-11-22 05:44

Here is a regex that works fine in most regex implementations:

(?

This matches .js for a string which ends with .js exc

6条回答
  •  忘掉有多难
    2020-11-22 06:28

    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)    ));

提交回复
热议问题