How to set variable within the Match Method (String)

2

What I want is to include the variable within (/.../) and not its value.

Code:

var str = 'Seu texto aqui!';

if (str.match(/texto/)) {
        alert('Palavra encontrada.');
}

Instead of manually defining, I want something dynamic coming from a variable.

Example:

var res = document.getElementById('txt').value = 'texto';

var str = 'Seu texto aqui!';

if (str.match(/res/)) {
        alert('Palavra encontrada.');
}

But it does not work (/res/) , as I can not figure out how to play a variable assignment within the match (String) method

    
asked by anonymous 25.03.2017 / 13:25

1 answer

1

You can use the new RegExp constructor like this:

var res = 'texto';
var regex = new RegExp(res);

var str = 'Seu texto aqui!';
if (str.match(regex)) {
  alert('Palavra encontrada.');
}

In case of plain text you can also use String.indexOf , in this case like this:

var res = 'texto';

var str = 'Seu texto aqui!';
if (str.indexOf(res) > -1) {
  alert('Palavra encontrada.');
}
    
25.03.2017 / 13:28