How to set variable within match method (String)

Asked

Viewed 932 times

2

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

Code:

var str = 'Seu texto aqui!';

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

Instead of setting manually, I want something dynamic 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 doesn’t work (/res/), because I’m not able to figure out how to play an assignment of the variable within the method match (String)

1 answer

1


You can use the constructor new RegExp thus:

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

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

In simple text cases you can also use the String.indexof, in that case:

var res = 'texto';

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.