I am trying to take the value of an input text field and use it within a regular expression. Here's what I have to match the start of a line.
regex = new RegExp('^' + inputValue, 'i')
It works fine for regular strings that start have alphanumeric characters, but I am using this for dollar amounts as well. When the input field starts with a '$' (dollar sign) i get varying results.
How can I escape the variable above to be viewed as a simple string? I've tried this, but no luck:
regex = new RegExp('^[' + inputValue + ']', 'i')
                In a regular expression, variable values are created by parenthetical statements.
Solution 1. let year = 'II'; let sem = 'I'; let regex = new RegExp(`${year} B. Tech ${sem} Sem`, "g"); You need to pass the options to the RegExp constructor, and remove the regex literal delimiters from your string.
Escape converts a string so that the regular expression engine will interpret any metacharacters that it may contain as character literals.
Probably one of the better implementations I've seen
http://phpjs.org/functions/preg_quote:491
Copied below for posterity
function preg_quote (str, delimiter) {
    // Quote regular expression characters plus an optional character  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/preg_quote    // +   original by: booeyOH
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // *     example 1: preg_quote("$40");
    // *     returns 1: '\$40'
    // *     example 2: preg_quote("*RRRING* Hello?");
    // *     returns 2: '\*RRRING\* Hello\?'
    // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");    // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
    return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With