简体   繁体   English

如何使用变量编写此 RegExp /^\s*FirstName\s*$/? 我想用变量替换 FirstName?

[英]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.

相关问题 我如何在 javascript user[0].firstName 中替换为 user.firstName - how do i replace in javascript user[0].firstName with user.firstName 如何检查姓氏和名字的大写字母? - How to check if firstname's and lastname's first characters are uppercase? 如何将 firstName 和 lastName 添加到 fullName? - How can I add firstName and lastName to fullName? 如何将变量s写入状态? - How to write the variable s in state? 我如何在反应中将名字/姓氏更改为名字/姓氏? 问题是它来自后端 - how can i change firstname/lastname to firstName/lastName in react? the problem is that it comes from the backend JS/如何通过名字和姓氏输入进行搜索,但如果我在名字后键入空格也可以工作 - JS/ How to search with input by firstname and lastname but also work if i type space after firstname 使用jQuery将文本替换为变量的值 - replace text to variable's value using jquery 如何检查数据库中已经存在的名字并给出错误消息? - How can i check firstname already in the database and give a error message? 如何在使用 jquery 提交的名字中允许空格 - How to allow blank space in firstname filed using jquery 如何过滤外部 JSON 数据并使用 Javascript 获取名字? - How to filter external JSON data and get firstName using Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM