Home > front end >  regex: get match and remaining string with regex
regex: get match and remaining string with regex

Time:12-14

I want to use the enter image description here

as you can see in the image I need to separate the match from the rest of the string to be able to apply some style or any other process separately.

/**
 * INPUT 
 * 
 * input: 'las vegas'
 * pattern: 'las'
 *
 *
 * EXPECTED OUTPUT
 * 
 * match: 'las'
 * remaining: 'vegas'
 */

CodePudding user response:

Get the match then replace the match with nothing in the string, and return both results.

function matchR(str, regex){
    // get the match
    var _match = str.match(regex);
    
    // return the first match index, and the remaining string
    return {match:_match[0], remaining:str.replace(_match, "")};
}

CodePudding user response:

Here is a function that takes the user input and an array of strings to match as as parameters, and returns an array of arrays:

const strings = [
  'Las Cruces',
  'Las Vegas',
  'Los Altos',
  'Los Gatos',
];

function getMatchAndRemaining(input, strings) {
  let escaped = input.replace(/[.* ?^${}()|[\]\\]/g, '\\$&');
  let regex = new RegExp('^('   escaped   ')(.*)$', 'i');
  return strings.map(str => {
    return (str.match(regex) || [str, '', str]).slice(1);
  });  
}

//tests:
['l', 'las', 'los', 'x'].forEach(input => {
  let matches = getMatchAndRemaining(input, strings);
  console.log(input, '=>', matches);
});

Some notes:

  • you need to escape the user input before creating the regex, some chars have special meaning
  • if there is no match, the before part is empty, and the remaining part contains the full string
  • you could add an additional parameter to the function with style or class to add to the before part, in which case you would return a string instead of an array of [before, remaining]
  • Related