Llama Obama Llama Obama - 3 months ago 17
Javascript Question

Javascript regex error " /?/: nothing to repeat " It worked fine earlier

I'm trying to clear a string of any invalid characters to be set as a directory.
Tried a number of methods and this one eventually worked[custom encoding] but now it doesn't, it says "nothing to repeat" in the console. What does that mean? using Chrome.

Here's the code(using random string):

var someTitle = "wa?";
var cleanTitle = cleanTitle(someTitle);

function cleanTitle(title){

var obstructions = ['\\','/',':','*','?','"','<','>','|'];
var solutions = [92,47,58,42,63,34,60,62,124];
var encodedTitle = title;

for (var obstruction = 0; obstruction < obstructions.length; obstruction++){
var char = obstructions[obstruction];

if (encodedTitle.includes(char)){
var enCode = "__i!__"+solutions[obstruction]+"__!i__";
var rEx = new RegExp(char,"g");
encodedTitle = encodedTitle.replace(rEx,enCode);
}
}

console.log("CLEAN: "+title);
console.log("ENCODED: "+encodedTitle);


return encodedTitle;
}


Heres the error:


Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to
repeat


It points to this line ->
var rEx = new RegExp(char,"g");

Answer

You need to escape some characters when using them as literals in a regular expression. Among those are most of the characters you have in your array.

Given your function replaces the obstruction characters with their ASCII code (and some wrapping __i!__), I would suggest to make your function a bit more concise, by performing the replacement with one regular expression, and a callback passed to .replace():

function cleanTitle(title){
    return title.replace(/[\\/:*?"<>|]/g, function (ch) {
        return "__i!__"+ch.charCodeAt(0)+"__!i__";
    });
}  

var someTitle = "wh*r* is |his?";
var result = cleanTitle(someTitle);

console.log(result);

...and if you are in an ES6 compatible environment:

var cleanTitle = t=>t.replace(/[\\/:*?"<>|]/g, c=>"__i!__"+c.charCodeAt(0)+"__!i__"); 

var someTitle = "wh*r* is |his?";
var result = cleanTitle(someTitle);

console.log(result);