erosman erosman - 3 years ago 293
Javascript Question

Converting user input strings with Special characters to regular expression

Note: there was a similar question but since it didn't have 'Special characters' and the problem here is only with 'Special characters', I posted a new question.

I have a list (from user input textarea) of Regular Expression representations:

Example: (simplified)

// starting point is a string like this one
let str = `/ab+c/
/Chapter (\d+)\.\d*/

I need to convert them into an array to check (for validity) and prepare each line e.g. (simplified)

let arr = str.split(/[\r\n]+/);

for (let i = 0, len = arr.length; i < len; i++) {

arr[i] = arr[i].slice(1, -1); // removing the start/end slashes
// problem with double slashing the Special characters
// it doesn't give the required result
arr[i] = arr[i].replace(/\\/g, '\\$&');
// same result with replace(/\\/g, '\\\\')

Finally, convert them into one RegEx object

let regex = new RegExp(arr.join('|'), 'i');

console.log(regex.test('dbbbd')); // true
console.log(regex.test('256')); // false

I must be missing something here.


I missed the point that the data that comes from a textarea (or similar) doesn't need to be escaped at all. When I was testing the code, I was testing it like above which didn't work.

Answer Source

Lets use the "change" event on <textarea> so that once the user changes the content and clicks outside, we just access the value property of it we can then construct the composite RegExp object. I haven't had the need to escape the \ characters at all.

Just copy paste the following to the text area and click outside.

/Chapter (\d+)\./

var myTextarea = document.getElementById("ta");

myTextarea.addEventListener("change", function(e) {
  var str = e.currentTarget.value.split(/[\r\n]+/)
                                 .map(s => s.slice(1, -1))
      rgx = new RegExp(str, "i")
  console.log(`Derived RegExp object: ${rgx}`);
  console.log(`Testing for 'dbbbd': ${rgx.test('dbbbd')}`); // true
  console.log(`Testing for '256': ${rgx.test('256')}`);     // true
#ta {
  width: 33vw;
  height: 50vh;
  margin-left: 33vw;
<textarea id="ta"></textarea>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download