escaping question mark in regex javascript - javascript

This is a simple question I think.
I am trying to search for the occurrence of a string in another string using regex in JavaScript like so:
var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";
var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");
if(content.search(gent) != -1){
alert('worked');
}
This doesn't work because of the ? character....I tried escaping it with \, but that doesn't work either. Is there another way to use ? literally instead of as a special character?

You need to escape it with two backslashes
\\?
See this for more details:
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm

You should use double slash:
var regex = new RegExp("\\?", "g");
Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"
And "\\?", becomes "\?"

You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;

Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:
var re = /I like your Apartment\. Could we schedule a viewing\?/g;
^^ ^^
Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:
var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");
And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
A must-read: RegExp: Description at MDN.

Related

regex matching QUESTION MARK in url [duplicate]

This is a simple question I think.
I am trying to search for the occurrence of a string in another string using regex in JavaScript like so:
var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";
var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");
if(content.search(gent) != -1){
alert('worked');
}
This doesn't work because of the ? character....I tried escaping it with \, but that doesn't work either. Is there another way to use ? literally instead of as a special character?
You need to escape it with two backslashes
\\?
See this for more details:
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
You should use double slash:
var regex = new RegExp("\\?", "g");
Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"
And "\\?", becomes "\?"
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;
Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:
var re = /I like your Apartment\. Could we schedule a viewing\?/g;
^^ ^^
Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:
var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");
And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
A must-read: RegExp: Description at MDN.

Javascript Replace, string with comma

I have a string that contains multiple occurrences of ],[ that I want to replace with ]#[
No matter what I try I cant get it right.
var find = '],[';
var regex = new RegExp(find, "g");
mytext.replace(regex, ']#[')
Doesn't work
mytext = mytext.replace(/],[/g,']#[');
Doesn't work
Any idea where I am going wrong?
The answer is that [ and ] are special characters in the context of regular expressions and as such need to be escaped either by means of \ i.e. to match ] you write [ when you use the convenient Javascript shorthand for regular expressions that you can find in the code below:
var regex= /\],\[/g
var result = mytext.replace(regex, ']#[')
Please check out the following jsFiddle: http://jsfiddle.net/JspRR/4/
As you can see the important bit is escaping the ] and the [ when constructing the regular expression.
Now if you did not want to use the Javascript regular expressions shorthand, you would still need to have the same escaping. However, in that case the \ character will need to be escaped itself ( ... by itself!)
var regex = new RegExp("\\],\\[", "g");
var result = mytext.replace(regex, ']#[')
The reason your example doesn't work is because normally square brackets represents a character class and therefore you need to escape them like so
var find = '\\],\\[';
var regex = new RegExp(find, "g");
mytext.replace(regex, ']#[')
You can also use a regex literal
mytext.replace(/\],\[/g, "]#[");
Try this:-
mytext.replace(/\],\[/g, ']#[')
Square brackets are special characters inside a regular expression: they are used to define a character set.
If you want to match square brackets in a regexp, you have to escape them, using back slash.
"[1],[2],[3]".replace(/\],\[/g, "]#[");
Or, in case you use the builtin constructor:
"[1],[2],[3]".replace(new RegExp("\\],\\[", "g"), "]#[");
In both case we have to use the g flag so that the regular expression can match all the occurrences of the searched string.
var str = "[1],[2],[3]";
console.log(str.replace(/\],\[/g, "]#["));
console.log(str.replace(new RegExp("\\],\\[", "g"), "]#["));
var str = "[1],[2],[3]";
var replaced = str.replace('],[', ']#[');

build Regex string with js

<script>
var String = "1 Apple and 13 Oranges";
var regex = /[^\d]/g;
var regObj = new RegExp(regex);
document.write(String.replace(regObj,''));
</script>
And it works fine - return all the digits in the string.
However when I put quote marks around the regex like this:
var regex = "/[^\d]/g"; This doesn't work.
How can I turn a string to a working regex in this case?
Thanks
You can create regular expressions in two ways, using the regular expression literal notation, or RegExp constructor. It seems you have mixed up the two. :)
Here is the literal way:
var regex = /[^\d]/g;
In this case you don't have use quotes. / characters at the ends serve as the delimiters, and you specify the flags at the end.
Here is how to use the RegExp constructor, in which you pass the pattern and flags (optional) as string. When you use strings you have to escape any special characters inside it using a '\'.
Since the '\' (backslash) is a special character, you have to escape the backslash using another backslash if you use double quotes.
var regex = new RegExp("[^\\d]", "g");
Hope this makes sense.
As slash(\) has special meaning for strings (e.g. "\n","\t", etc...), you need to escape that simbol, when you are passing to regexp:
var regex = "[^\\d]";
Also expression flags (e.g. g,i,etc...) must be passed as separate parameter for RegExp.
So overall:
var regex = "[^\\d]";
var flags = "g";
var regObj = new RegExp(regex, flags);

javascript - insert a variable into regexp

I have the following which works fine, allowing a form field to be valid if blank or containing the word "hello" or passing the other validation...
var re = new RegExp(/^$|^[hello]|^([FG]?\d{5}|\d{5}[AB])$/);
but I want to make the word "hello" be the value of a variable.
I have tried this but it no longer seems to work:
var i = "hello";
var re = new RegExp('/^$|^['+i+']|^([FG]?\d{5}|\d{5}[AB])$/');
There are several things wrong in your code.
RegExp expects a string, not a regex literal like you pass in the first case. It seems that RegExp is smart enough though and detects that you are passing a regex literal. So your first example works by coincidence and is the same as:
var re = /^$|^[hello]|^([FG]?\d{5}|\d{5}[AB])$/;
The / are not part of the expression, they are the delimiters to denote a regex literal, much like quotation marks (') indicate a string literal. Hence, if you pass the expression as string to RegExp, it should not contain /.
Since the backslash is the escape character in strings as well, in order to create a literal backslash for the expression you have to escape it: \\.
[hello] does not test for for the word hello, it matches either h, e, l or o, thus it is equivalent to [ehlo].
With all that said, your code should be:
var i = "hello";
var re = new RegExp('^$|^'+i+'|^([FG]?\\d{5}|\\d{5}[AB])$');
Drop the leading and trailing / characters and your reg exp is not going what you expect. Double up the \ characters so they are escaped. Also [] means match any of these characters.
Basic example
var str = "hello world";
var word = "hello"
var re = new RegExp("^" + word + "\\s?")
console.log( str.match(re) );

Easy Javascript Regex Question

Why doesn't this assign prepClass to the string selectorClass with underscores instead of non alpha chars? What do I need to change it to?
var regex = new RegExp("/W/", "g");
var prepClass = selectorClass.replace(regex, "_");
A couple of things:
If you use the RegExp constructor, you don't need the slashes, you are maybe confusing it with the syntax of RegExp literals.
You want match the \W character class.
The following will work:
var regex = new RegExp("\\W", "g");
The RegExp constructor accepts a string containing the pattern, note that you should double escape the slash, in order to get a single slash and a W ("\W") in the string.
Or you could simply use the literal notation:
var regex = /\W/g;
Recommended read:
Regular Expressions (MDC)

Categories

Resources