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);
+ for concatenation. You also need to escape \b+ for concatenation in new RegExp as it creates a regex from string. But you are correct that you cannot use + in /.*/g syntax as it will be evaluatedIf 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];
let str = 'B ad ga'; let result = str.search('a'); document.write(result); but when i run this code, answer is: "2" so search() like indexOf()