How to Escape Regular Expression Special Characters Using JavaScript

How can I escape special characters in regex and Javascript

On this line:

if (userInput.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~ ()]/g,"").match(new RegExp('(^|\\s)'+key.toLowerCase()+'(\\s|$)')))  {{

you remove spaces (there is a space in the character class in /[.,\/#!$%\^&\*;:{}=\-_`~ ()]/g). That is why your regex (that you build with new RegExp('(^|\\s)'+key.toLowerCase()+'(\\s|$)')) matches only when the string is equal to key, it expects the key in between whitespaces or start/end of string.

You need to remove the space from replacement and apply this operation both on the input and key:

if (userInput.replace(/[.,\/#!$%^&*;:{}=\-_`~()\\]/g,"").match(new RegExp('(^|\\s)'+key.replace(/[.,\/#!$%^&*;:{}=\-_`~()\\]/g,"")+'(\\s|$)', 'i')))  {{

Note ^ and ; need no escaping. I also added a backslash to the special char character class.

Note there is no need to turn the case to lower, you can simply pass the i case insensitive flag to regex.

Is there a RegExp.escape function in JavaScript?

The function linked in another answer is insufficient. It fails to escape ^ or $ (start and end of string), or -, which in a character group is used for ranges.

Use this function:

function escapeRegex(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

While it may seem unnecessary at first glance, escaping - (as well as ^) makes the function suitable for escaping characters to be inserted into a character class as well as the body of the regex.

Escaping / makes the function suitable for escaping characters to be used in a JavaScript regex literal for later evaluation.

As there is no downside to escaping either of them, it makes sense to escape to cover wider use cases.

And yes, it is a disappointing failing that this is not part of standard JavaScript.

How to escape special characters in regular expressions

SOLUTION

You can add and use a function escapeRegExp() that will escape special
characters as found in MDN - Regular Expressions article:

function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// ... skipped ...

table.column('myColumn:name').search(escapeRegExp(searchString), true, false, true).draw();

DEMO

See this jsFiddle for code and demonstration.

Escape regex special characters in javascript but still retain string integrity for matching keywords

You need to escape each non-whitespace chunk you want to search for and highlight. Also, there is no need to use a callback inside replace to replace with a whole match, you may use a $& backreference.

See the updated JS:

vm = new Vue({
el: "#app",
data() {
return {
search: null,
message: 'Search this text for matches (check the bracketed area too)'
};
},
computed: {},
methods: {
highlight (str) {
var replacedStr = (this.search || '').trim().split(/\s+/).map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')).join("|");
return str.replace(new RegExp(replacedStr, 'gi'),
'<span class="teal--text text--darken-1 font-weight-bold">$&</span>');
}
}
});

Here:

  • .trim().split(/\s+/).map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')).join("|") - trims the input string with trim(), then splits out all non-whitespace chunks with .split(/\s+/), then these chunks are escaped with .map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')), and then .join("|") creates a regex pattern with a list of alternatives.
  • In the '<span class="teal--text text--darken-1 font-weight-bold">$&</span>' string replacement pattern, the $& parts stands for the whole match value.

How to escape regex special characters from array using php to use in javascript

You could use array_map() with preg_quote() like this :

$arr = array("+1", "1+4"); 
echo implode("|", array_map('preg_quote', $arr));

Outputs :

\+1|1\+4

To get the final pipe :

$arr = array("+1", "1+4" , ""); 
echo implode("|", array_map('preg_quote', $arr)) ;
// Or
$arr = array("+1", "1+4");
echo implode("|", array_map('preg_quote', $arr)) . "|" ;

Outputs :

\+1|1\+4|

Regex Javascript escape special characters plus characters limit

Remove + after {1,35} and escape only special characters:

var regex = /^\s*([0-9a-zA-Z\s,\-()'_@~&*=.`]{1,35})\s*$/;
console.log(regex.test(" asdfghjkl "))console.log(regex.test(" asdf'&@() "))console.log(regex.test(" asdfghjklasdfghjklasdfghjklasdfghjklasdfghjkl "))

Does regex syntax provide a way of escaping a whole string, rather than escaping characters one by one?

It appears that regex does not offer such a syntax, at least for Javascript. It is possible, however, to proceed as follows:

  1. use a string and automatically escape all the special characters in it,
    as indicated here: Javascript regular expression - string to RegEx object
  2. concatenate that string with strings representing the rest of the expression you want to create
  3. transform the string into a regex expression as indicated in Escape string for use in Javascript regex .


Related Topics



Leave a reply



Submit