[英]How to write this RegExp /^\s*FirstName\s*$/ using a variable? I want to replace FirstName with a variable?
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.我正在尝试编写以空格或单词开头的 RegExp,但我想使用变量传递单词。 Does anyone have idea about this?
有没有人知道这个?
Regex express is just a normal string, you can replace the variable with string method and then use it as pattern. Regex express 只是一个普通的字符串,您可以用字符串方法替换变量,然后将其用作模式。 For example:
例如:
const getPattern = function (placeholder) {
return new RegExp(`\\s*${placeholder}\\s*$`);
}
const matcher = getPattern('firstName');
console.log(matcher.exec('my firstName '));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.