-1

How can I replace the "@" with the constant “begins” in the regular expression

function matchAlltext() {
      const str = document.getElementById('textinput').value;
      const begins = document.getElementById('begins').value;
      const regexp = new RegExp(/@\w+/ig);
      let matchAll = str.matchAll(regexp);
      matchAll = Array.from(matchAll);
      document.getElementById('textoutput').value = matchAll;
    }

I need to find all the words in the text starting with the character entered in the input field

Vladislav
  • 476
  • 2
  • 13
  • @YevgenGorbunkov Your code is a syntax error, nothing else – baao May 25 '20 at 11:09
  • 1
    Does this answer your question? [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) [How to use a variable inside a RegEx pattern?](https://stackoverflow.com/questions/45451533/how-to-use-a-variable-inside-a-regex-pattern) – teg_brightly May 25 '20 at 11:22

1 Answers1

1

Like this?

const str = "abc abc abc"
const begins = "a"
const regexp = new RegExp(begins + "\\w+","ig");
let matchAll = str.matchAll(regexp);
matchAll = Array.from(matchAll);
console.log(matchAll); //logs [["abc"], ["abc"], ["abc"]]
Dostrelith
  • 922
  • 5
  • 13
  • Doesn't work with some symbols. If I want to find words starting with $,?,+ and others that are indicated as special symbols in regular expressions, how can I do this? – Vladislav May 25 '20 at 12:01
  • For a simple case, you can change to: const regexp = new RegExp("\\" + begins + "\\w+","ig");. The only character it won't work on is "\" itself. – Dostrelith May 25 '20 at 12:08