How can I convert a PHP regex-based string sanitization function into JavaScript?

Solution:

You can sanitize a string for use in JavaScript (e.g., for IDs or variable names) using a regular expression:


function sanitizejs(str) {
    return str
        .trim()                     // remove leading/trailing spaces
        .replace(/[^A-Z0-9]+/ig, "_") // replace non-alphanumeric characters with "_"
        .toLowerCase();             // convert to lowercase
}

console.log(sanitizejs('Test String - 20AS(AE)0121 '));
// Output: test_string_20as_ae_0121

✅ Explanation:

trim() → removes spaces at the start and end.

replace(/[^A-Z0-9]+/ig, “_”) → replaces all non-alphanumeric characters with underscores.

toLowerCase() → makes the string lowercase.