JavaScript regex for string literal? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a RegExp.escape function in Javascript?
I'm currently using: var keywords = new RegExp(req.params.keywords, 'i');
The catch is, if req.params.keywords == '.*', this will match anything, what I want is for it to match .* literally, as in \.\*\
Is there a more elegant solution than escaping every passed single character with a \?

If you want to match literally, instead of using the regular expressions included in the string, don't use a regular expression. Use the string indexOf() function to see if a string is contained withing another one.
For case insensitive matching, you convert each string to, say, lower case before the match.
var searchForString = req.params.keywords.toLowerCase();
var searchInString = xxx.toLowerCase();
if (searchInString.indexOf(searchForString) >= 0) {
... then it matches ...
}

Related

Regular Expression to check Special characters except hypen and forwardslash [duplicate]

This question already has answers here:
Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./
(7 answers)
Closed 3 years ago.
I would like to know regex code to check whether it contains Special characters other than hypen and forwardslash in javascript
function containsSpecialCharacters(str){
var regex = /[~`!#$%\^&*+=\-\[\]\';,/{}|\\":<>\?]/g;
return regex.test(str);
}
var result = containsSpecialCharacters("sample"); // false
var result = containsSpecialCharacters("sample-test"); // false
var result = containsSpecialCharacters("sample++"); // true
var result = containsSpecialCharacters("/sample/test"); // false
You can use a normal regex to search for all ASCII special characters, like this one, and then just remove the hypen and backslash:
/[!$%^&*()_+|~=`{}\[\]:";'<>?,.]/
If you want to avoid any other special character, you just have to remove it from the regex.
You can test this regex here: https://regex101.com/r/gxYiGp/2
If you need to support only English characters, it would be far easier to list the exceptions than those you wish to match:
/[^\w\s\\\-]/.test(myString);
As noted, though, this will fail if you need to support international characters.
you can just negate it so it looks shorter, like this :
[^\s\w-]

Javascript regular expression to validate whether both () brackets are present [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
Techies,
I'm working on kind of calculator, am not much comfortable with regex. My need is JavaScript regular expression to validate whether both ( ) brackets are present, there may be some character inside the brackets.
suggestions please
Simple regex:
var string = '1234 + 1234 (5)';
if (string.match('\(|\)')) {
console.log('() found')
}
Simply matching
\(.*\)
will match if both an opening, and a closing parentheses are present. (Parentheses need to be escaped since it's a special character in regex.) .* matches anything, including an empty string.
But I assume you'd want to allow strings without any parentheses as well. This regex allows for any number of pairs of parentheses (not nested) or none at all:
^[^()]*(?:\([^()]*\)[^()]*)*$
It matches start of string ^, a string of any length not containing parentheses [^()]*. Then any number of the combination 1. Opening P(arentheses) 2. Any length string w/o P's. 3. A closing P. 4. Any length string w/o P's. (Possibly repeated any number of times.) Finally it matches end of string $.
Working example (Type an expression into the input control, and press Enter.):
var inputExpression = document.getElementById("expression");
function testExpression(){
console.log(inputExpression.value.match(/^[^()]*(?:\([^()]*\)[^()]*)*$/) ? "Well formed" : "Unbalanced parentheses");
// inputExpression.value = '';
}
inputExpression.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
testExpression();
}
});
Enter an expression:<input id="expression" type="text" onBlur="testExpression()"/>

How to match with new RegExp exactly [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 5 years ago.
I have this string:
var str = "https://www.mysite.se/this-match?ba=11"
I need to match it exactly (between / and ?), so only this-match matches, not this-ma or anything (shorter) that is contained in this-match.
I.e:
var myre = new RegExp('\/this-ma\?');
Still matches:
myre.exec(str)[0]
"/this-ma"
How can I avoid that a shorter string contained in this-match does give a match?
The definition of your regex is wrong. You'd think that \? would match literal ? character, instead of being non-greedy modifier. Not true. Quite the opposite, in fact.
var myre = new RegExp('\/this-ma\?');
> /\/this-ma?/
The backslash here works within the string literal, and outputs single ? to regex, which becomes non-greedy modifier. Use the regex literal.
var myre = /\/this-ma\?/

Matching content within a string with one regex [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Simple way to use variables in regex
(3 answers)
Closed 10 years ago.
I am looking for a way to RegEx match for a string (double quote followed by one or more letter, digit, or space followed by another double quote). For example, if the input was var s = "\"this is a string\"", I would like to create a RegEx to match this string and produce a result of [""this is a string""].
Thank you!
Use the RegExp constructor function.
var s = "this is a string";
var re = new RegExp(s);
Note that you may need to quote the input string.
This should do what you need.
s =~ /"[^"]*"/
The regex matches a double quote, followed by some number of non-quotes, followed by a quote. You'll run into problems if your string has a quote in it, like this:
var s = "\"I love you,\" she said"
Then you'll need something a bit more complicated like this:
s =~ /"([^"]|\\")*"/
I just needed a pattern to match a double quote followed by one or more characters(letters, digits, spaces) followed by another double quote so this did it for me:
/"[^"]*"/

Javascript RegEx Not Working [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
I have the following javascript code:
function checkLegalYear() {
var val = "02/2010";
if (val != '') {
var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");
if (regEx.test(val)) {
//do something
}
else {
//do something
}
}
}
However, my regEx test always returns false for any value I pass (02/2010). Is there something wrong in my code? I've tried this code on various javascript editors online and it works fine.
Because you're creating your regular expression from a string, you have to double-up your backslashes:
var regEx = new RegExp("^(0[1-9]|1[0-2])/\\d{4}$", "g");
When you start with a string, you have to account for the fact that the regular expression will first be parsed as such — that is, as a JavaScript string constant. The syntax for string constants doesn't know anything about regular expressions, and it has its own uses for backslash characters. Thus by the time the parser is done with your regular expression strings, it will look a lot different than it does when you look at your source code. Your source string looks like
"^(0[1-9]|1[0-2])/\d{4}$"
but after the string parse it's
^(0[1-9]|1[0-2])/d{4}$
Note that \d is now just d.
By doubling the backslash characters, you're telling the string parser that you want single actual backslashes in the string value.
There's really no reason here not to use regular expression syntax instead:
var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;
edit — I also notice that there's an embedded "/" character, which has to be quoted if you use regex syntax.

Categories

Resources