2
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().

ButchMonkey
  • 1,873
  • 18
  • 30

5 Answers5

3

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;
ButchMonkey
  • 1,873
  • 18
  • 30
2

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);
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
1

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);
SparkFountain
  • 2,110
  • 15
  • 35
1

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];
PHP Guru
  • 1,301
  • 11
  • 20
  • Thank you for your help too i maked search engine for my blog but if i use indexOf() visitor search value "a" then it show all articles ... İ just want to filter with regex to make results better... – Soru İşareti Jan 29 '20 at 16:05
  • Why do you want to show the index of the matched expression? That's what String.prototype.search() does. – PHP Guru Jan 29 '20 at 16:13
  • `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() – Soru İşareti Jan 29 '20 at 16:54
  • Yes. It's exactly like indexOf except it expects a regular expression. – PHP Guru Feb 01 '20 at 21:46
1

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)
Siva K V
  • 10,561
  • 2
  • 16
  • 29