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\?/
Related
This question already has answers here:
How can I put [] (square brackets) in RegExp javascript?
(8 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
I am trying to replace the following in a Regex:-
[company-name]
Using Regex I would expect I could use was to use:-
str.replace(/[company-name]/g, 'Google');
But I know that the regex will replace any matching letter.
How am I able to replace the [company-name] with Google using JS Regex?
Thanks in advance for your help.
But I know that the regex will replace any matching letter.
This is only the case because you have encapsulated your characters in a character class by using [ and ]. In order to treat these as normal characters, you can escape these using \ in front of your special characters:
str.replace(/\[company-name\]/g, 'Google');
See working example below:
const str = "[company-name]",
res = str.replace(/\[company-name\]/g, 'Google');
console.log(res);
You need to escape the starting [ as well, in this case as they are special characters too:
var str = "I am from [company-name]!";
console.log(str.replace(/\[company-name]/gi, "Google"));
str = "[company-name]'s awesome!";
console.log(str.replace(/\[company-name]/gi, "Google"));
you could do it this way :
var txt = "So I'm working at [company-name] and thinking about getting a higher salary."
var pattern = /\[.+\]/g;
console.log(txt.replace(pattern, "Google"))
You should escape special characters like square brackets in this case.
Just use:
str.replace(/\[company-name\]/g, 'Google');
This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 7 years ago.
I have been staring at these two flavors of same regex and can't figure out why the outcome is different:
var projectName="SAMPLE_PROJECT",
fileName="1234_SAMPLE_PROJECT",
re1 = new RegExp('^(\d+)_SAMPLE_PROJECT$','gi'),
re2 = /^(\d+)_SAMPLE_PROJECT$/gi,
matches1 = re1.exec(fileName),
matches2 = re2.exec(fileName);
console.log(matches1);//returns null
console.log(matches2);//returns correctly
Here is the jsbin : https://jsbin.com/badoqokumu/edit?html,js,output
Any idea what I must be doing wrong with instantiating RegExp?
Thanks.
In the first case, you have a string literal, which uses \ to introduce escape sequences. \d in a string is just d. If you want \d, you need to type \\d instead.
In the second case, you have a regular expression literal, which does not interpret \ as a string escape sequence.
This question already has answers here:
JavaScript Regex, where to use escape characters?
(3 answers)
Closed 8 years ago.
I am having a small issue with placing a RegExp pattern inside a string, I have 2 patterns which are both really the same. The first doesn't work I presume due to the \d - is it being seen as an escape character?
var pattern = '^.{1,5}-\d{1,5}$'; // Doesn't work
var pattern = '^[a-zA-Z]{1,5}-[0-9]{1,5}$'; // Works
Is there anyway around this ? apart from replacing the \d with [0-9]?
Here is the extra code I am using
var regex = new RegExp(pattern);
var result = regex.test(value);
Thanks in advance
As found in the documentation you have several different ways to create a RegExp
Regular expression literal,
var regex = /^.{1,5}-\d{1,5}$/;
Constructor function of the RegExp object
var regex = new RegExp("^.{1,5}-\\d{1,5}$");
since it is a string, you need to escape any \
Same for \w and other backslashed chars
The second version is mostly used if you have variables you need to add to the regexp
If you want the way your are writing the regex to work, you can double escape the d:
var pattern = '^.{1,5}-\\d{1,5}$'; // Should work
var regex = new RegExp(pattern);
Otherwise, you can use the regex directly using the delimiters /:
var pattern = /^.{1,5}-\d{1,5}$/;
In the first instance, you are storing the pattern in a string, and the actual characters that are being passed to the variables are: ^.{1,5}-\d{1,5}$ because \d has no meaning in a string, but \\d is a backslash and a literal d. You can try putting a backslash in a string:
console.log('\'); // Won't run
console.log(' \ '); // Returns a space
console.log('\n'); // Returns a newline character
So that if you mean a literal backslash, you have to escape it.
Using:
var pattern = '^.{1,5}-\\d{1,5}$'; // Should work
var regex = new RegExp(pattern);
should be faster though, if you are using the regex several times, because here, you are compiling the regex so that you can use it multiple times.
The other way will require compiling the regex each time it is called for.
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:
/"[^"]*"/
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 ...
}