jon-myers / idtp

An Interactive Digital Transcription Platform for Hindustani Music
https://swara.studio
2 stars 1 forks source link

regular expression handling in search bar of filterable table #478

Open jon-myers opened 2 days ago

jon-myers commented 2 days ago

Screen goes black and gets this console error when typign "Vocal ( ... ":

SyntaxError: Invalid regular expression: /(vocal ()/gi: Unterminated group (at FilterableTable.vue:204:49) at new RegExp () at FilterableTable.vue:204:49 at Proxy.map () at FilterableTable.vue:201:20 at Proxy.map () at Proxy.highlightedData (FilterableTable.vue:200:32) at Ro.run (reactivity.esm-bundler.js:190:25) at get value (reactivity.esm-bundler.js:1171:39) at Object.get [as highlightedData] (runtime-core.esm-bundler.js:3488:30) at Object.get (runtime-core.esm-bundler.js:3132:32)

It seems to be that the parenthesis is a special character in a regular expression. Needs to be handled

jon-myers commented 2 days ago

here's what chatgpt thinks:

he issue you’re experiencing when typing “vocal (f…” into your search bar is likely due to the regular expression being dynamically constructed or used in your code without proper handling of special characters. Specifically, the parentheses are causing the issue because they are special characters in regular expressions.

To fix this, you should escape special characters in your search input before using it to construct a regular expression. Here’s how you can handle it:

  1. Escape special characters: Create a function to escape special characters in the search string.
  2. Use the escaped string to construct the regular expression:

Here’s an example of how you can do this:

// Function to escape special characters in a search string
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

// Your search input
let searchInput = "vocal (f..."; // Example input

// Escape special characters in the search input
let escapedInput = escapeRegExp(searchInput);

// Create a regular expression with the escaped input
let regex = new RegExp(escapedInput, 'gi');

// Example data to search
const data = ["vocal (foo)", "vocal (bar)", "instrumental"];

// Apply the regex to the data
const highlightedData = data.map(item => {
  return item.replace(regex, '<highlight>$&</highlight>');
});

console.log(highlightedData);