3

I want to use the RegExp constructor to run a regular expression against a string and let me get both the match and the remaining string.

the above is to be able to implement the following UI pattern:

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'
 */

2 Answers 2

2

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, "")};
}
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.