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 withtrim()
, 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:
- use a string and automatically escape all the special characters in it,
as indicated here: Javascript regular expression - string to RegEx object - concatenate that string with strings representing the rest of the expression you want to create
- transform the string into a regex expression as indicated in Escape string for use in Javascript regex .
Related Topics
Check/Uncheck Checkbox with JavaScript
Get the Element with the Highest Occurrence in an Array
Create Object from Class Name in Javasscript Ecmascript 6
How to Replace Innerhtml of a Div Using Jquery
In JavaScript, Why Is "0" Equal to False, But When Tested by 'If' It Is Not False by Itself
Check Whether Variable Is Number or String in JavaScript
Is the Underscore Prefix for Property and Method Names Merely a Convention
The Value of "This" Within the Handler Using Addeventlistener
How to Write a Named Arrow Function in Es2015
How to Destructure Onto an Existing Object? (JavaScript Es6)
Differencebetween 'New Object()' and Object Literal Notation
How to Share $Scope Data Between States in Angularjs Ui-Router
Promise.All Consumes All My Ram
Parseint VS Unary Plus, When to Use Which
Passing Environment-Dependent Variables in Webpack
Window.Location.Href and Window.Open () Methods in JavaScript