How would you put a special character inside a regexp variable ? [JS]

Hello everyone ! I’ve been struggling recently with a code I came up with to check if a character in a string has several occurence :

function hasUniqueChars(str){
    str = str.toLowerCase();
    for (i=0;i<str.length;i++) {
    var re = new RegExp(str[i] , "gi");
    if (str.match(re).length > 1) {
      return true
  return false

It has worked so far, but the problem is that if the string contains a special characters, aka [+ - / ? ! etc … ] the code will crash since you cannot use those characters as a string inside a regexp, you rather have to use a backslash to escape the expression.

So, does anyone know a way to pass a special character inside a variable and then inside a regexp? That would be of a great help. Thank you !

Have you solved Convert HTML Entities yet? a similar approach should work.

Nope, haven’t got there yet.

`I was thinking about doing something like

if str[i].match(/\W/) {re = new RegExp("/[" + str[i] + "]/", gi)}

but it doesn’t seem to do the trick :confused: I guess i’ll learn it eventually.

I would suggest mapping special characters to their escaped versions.