var str = "Visit tEsT!";
var ara = "test";
let n = str.search(/\b + ara + \b/i); // Sadly code doesn't run
document.getElementById("demo").innerHTML = n;
I want find ara
variable in str
variable with regex search()
.
var str = "Visit tEsT!";
var ara = "test";
let n = str.search(/\b + ara + \b/i); // Sadly code doesn't run
document.getElementById("demo").innerHTML = n;
I want find ara
variable in str
variable with regex search()
.
You need to define a new regex from a string in order to use variables.You can do this with new RegExp()
. You will also need the i
option for case insensitive mode.
var str = "Visit tEsT!";
var ara = "test";
var regex = new RegExp(`\\b${ara}\\b`, 'i'); // Evaluates to "/\btest\b/i"
let n = str.search(regex);
document.getElementById("demo").innerHTML = n;
You have to put variables like this in Regex:
var str = "Visit tEsT!";
var ara = "test";
let n = str.search(new RegExp(`\\b${ara}`,"i"));
console.log(n);
More secure way is to remove special chars:
str.replace(/[^A-Za-z0-9\s\n]/g,"")
var str = "Visit tEsT!";
var searchstr = "test &#";
let n = str.search(new RegExp(`\\b${searchstr.replace(/[^A-Za-z\\s\\n]/g,"")}`,"i"));
console.log(n);
In your regular expression, you cannot use the +
operator as a string concatenator. Instead, you could use for example template strings and create the regular expression with new RegExp
:
var str = "Visit tEsT!";
var ara = "test";
var regex = new RegExp(`\\b${ara}\\b`, 'gi'); // use 'gi' flags to search globally and ignore case
let n = str.search(regex);
console.log(n);
If you want the matched string, use match() instead. The return value n will be an array and its first value (n[0]) will be the matched string.
var str = "Visit tEsT!";
var ara = "test";
var regexp = new RegExp("\\b"+ara+"\\b", 'gi')
n = str.match(regexp);
document.getElementById("demo").innerHTML = n[0];
Using search
and match
multiple ways.
var str = "Visit tEsT!";
var ara = "test";
let n = str.search(new RegExp('\\b' + ara + '\\b', 'i'))
let n2 = str.match(new RegExp('\\b' + ara + '\\b', 'i')).index;
//document.getElementById("demo").innerHTML = n;
console.log(n, n2)