Javascript Regex: Как поместить переменную в регулярное выражение?
Но это, конечно, не работает:) Есть ли способ сделать это?
8 ответов
Update
В некоторых комментариях важно отметить, что вы можете захотеть escape эту переменную, если есть вероятность для вредоносного контента (например, переменная возникает из пользовательский ввод)
Вы можете использовать объект RegExp:
Затем вы можете построить regexstring любым способом.
Подробнее об этом можно узнать .
Чтобы создать регулярное выражение из переменной в JavaScript, вам нужно будет использовать конструктор RegExp со строковым параметром.
конечно, это очень наивный пример. Он предполагает, что input был правильно экранирован для регулярного выражения. Если вы имеете дело с пользовательским вводом или просто хотите сделать его более удобным для соответствия специальным символам, вам нужно выполнить специальные символы:
Вы всегда можете «ReGeX» + testVar + «ReGeX» регулярное выражение в виде строки, то есть «ReGeX» + testVar + «ReGeX» . Возможно, вам придется экранировать некоторые символы внутри вашей строки (например, двойные кавычки), но в большинстве случаев это эквивалентно.
Вы также можете использовать конструктор RegExp для передачи флагов (см. Документацию).
если вы используете литералы шаблона es6 вариант.
принятый ответ не работает для меня и не следует примерам MDN
см. раздел «Описание» в ссылке выше
Я бы пошел со следующим это работает для меня:
Здесь довольно бесполезная функция, которая возвращает значения, заключенные в определенные символы. 🙂
Вы можете создавать регулярные выражения в JS одним из двух способов:
- Использование литерала регулярного выражения — /ab<2>/g
- Использование конструктора регулярных выражений — new RegExp(«ab<2>«, «g») .
Литералы регулярных выражений являются константами и не могут использоваться с переменными. Это может быть достигнуто с помощью конструктора. Структура конструктора RegEx
Вы можете встраивать переменные как часть normalExpressionString. Например,
How to use variable inside regex in JavaScript? [SOLVED]
A regular expression is a powerful tool for matching text patterns. They can be used for searching, editing, and manipulating text. Furthermore, regular expressions are often used in search engines, text editors, and programming languages. They are also used in many different applications, such as validating email addresses and credit card numbers.
Regular expressions (regex) can be very simple or very complex, depending on what you want to match. For example, the regular expression «a» will match any single character, while the regular expression «a+» will match one or more characters.
Instead of directly specifying the characters we want to match, we can make the regex dynamically by accepting a variable containing the characters. In this article, we will discuss how to place a variable inside regex within the JavaScript environment.
Use RegExp to place a variable inside regex
If you need to use a variable in a regular expression in JavaScript, you have to use the RegExp constructor. This is because the regular expression is compiled when the constructor is called, and the variable won’t be replaced if you use a literal regular expression.
The RegExp constructor takes two parameters: the first is the regular expression itself, and the second is the flags parameter. The flags parameter is optional, and it can be used to set various flags on the regular expression, such as whether or not it is case-sensitive.
To use a variable in a regular expression, you have to make use of template literals and put the variable name inside of curly brackets which are preceded by a $ sign. For example, if you have a variable named name and you want to match it against the regular expression gi , you would use the following code:
If the variable name contains the value «John», the regular expression would match the string «John» and will still match the string «john».
Still use the RegExp constructor, we can try something a little different, and make use of a different pattern. Here, we want to only replace when pattern is matched and not Pattern .
However, if the str binding contained Pattern , it wouldn’t replace and will log pattern matching .
Summary
Regular expressions (regex) can be very simple or very complex, depending on what you want to match. There are many different ways to create regular expressions, but they all follow a similar format. The basic format of a regular expression is a series of characters that you want to match, followed by a series of characters that you do not want to match. But with a variable inside regex, we can dynamically change the words we want to replace or change or find. To achieve this, we can make use of the RegExp constructor.
References
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
RegExp
Когда регулярное выражение создается при помощи конструктора new RegExp(…) , необходимо помнить, что обратные слеши (\) должны экранироваться, например:
При использовании литерального формата, этого делать не нужно:
Обе записи эквивалентны. Первый вариант может понадобится, если вам придется генерировать регулярное выражение динамически.
Виды символов
В регулярных выражениях различают следующие виды символов:
Обычные символы
- A..z — английские буквы от A до z, строчные и заглавные;
- 0..9 — цифры;
- < >— фигурные скобки, кроме случаев, когда они составляют группу вида
(где n и m — числа) и её вариации; - = — равно;
- < — меньше;
- > — больше;
- — — минус;
- , — запятая;
- и др.
Специальные символы
- ( ) — круглые скобки;
- [ ] — квадратные скобки;
- \ — обраный слеш;
- . — точка;
- ^ — степень;
- $ — знак доллара;
- | — вертикальная черта;
- ? — вопросительный знак;
- + — плюс.
Формирование регулярного выражения
При формировании шаблона поиска используется близкий к классическому PCRE синтаксис.
How do you use a variable in a regular expression?
I would like to create a String.replaceAll() method in JavaScript and I’m thinking that using a regex would be most terse way to do it. However, I can’t figure out how to pass a variable in to a regex. I can do this already which will replace all the instances of «B» with «A» .
But I want to do something like this:
But obviously this will only replace the text «replaceThis» . so how do I pass this variable in to my regex string?
27 Answers 27
Instead of using the /regex\d/g syntax, you can construct a new RegExp object:
You can dynamically create regex objects this way. Then you will do:
As Eric Wendelin mentioned, you can do something like this:
This yields «regex matching .» . However, it will fail if str1 is «.» . You’d expect the result to be «pattern matching regex» , replacing the period with «regex» , but it’ll turn out to be.
This is because, although «.» is a String, in the RegExp constructor it’s still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful: