I am trying to write the RegExp that begins with either the space or the word, but I want to pass the word using the variable. Does anyone have idea about this?
            Asked
            
        
        
            Active
            
        
            Viewed 40 times
        
    -2
            
            
        - 
                    Did you try [How do you use a variable in a regular expression?](https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression?rq=1)? – ggorlen Dec 13 '22 at 04:52
1 Answers
1
            
            
        Regex express is just a normal string, you can replace the variable with string method and then use it as pattern. For example:
const getPattern = function (placeholder) {
  return new RegExp(`\\s*${placeholder}\\s*$`);
}
const matcher = getPattern('firstName');
console.log(matcher.exec('my firstName '));
 
    
    
        Saddle Point
        
- 21
- 2
