Constructor Regex in JavaScript - javascript

My code is as follows:
var regex = new RegExp ('(.*/*)');
console.log(regex);
I think the result is:
/(.*/*)/
But the actual result is:
/(.*\/*)/
Could someone please explain this for me?

The leading and trailing forward slashes are just how JavaScript represents a regex in string form and as a literal. The mean the same thing:
var regex = new RegExp ('(.*/*)');
is the same as
var regex = /(.*\/*)/;
It is important to escape the middle / otherwise it would interpret it as the end of the literal.

If you expect the last asterisk * to be literal you need to escape it, otherwise it's a quantifier in regex meaning "match between zero and unlimited times". It's also recommened to escape the forward slash /, even if it might work without doing so.
(.*\/\*)
If you want to match any string /* any string then use:
(.*\/\*.*)
https://regex101.com/r/aJ4eA4/1

Related

Javascript Regex for a partial string with slash [duplicate]

I don't have much experience with JavaScript but i'm trying to create a tag system which, instead of using # or #, would use /.
var start = /#/ig; // # Match
var word = /#(\w+)/ig; //#abc Match
How could I use a / instead of the #. I've tried doing var slash = '/' and adding + slash +, but that failed.
You can escape it like this.
/\//ig; // Matches /
or just use indexOf
if(str.indexOf("/") > -1)
You need to escape the / with a \.
/\//ig // matches /
You can escape it by preceding it with a \ (making it \/), or you could use new RegExp('/') to avoid escaping the regex.
See example in JSFiddle.
'/'.match(/\//) // matches /
'/'.match(new RegExp('/') // matches /
If you want to use / you need to escape it with a \
var word = /\/(\w+)/ig;
In regular expressions, "/" is a special character which needs to be escaped (AKA flagged by placing a \ before it thus negating any specialized function it might serve).
Here's what you need:
var word = /\/(\w+)/ig; // /abc Match
Read up on RegEx special characters here: http://www.regular-expressions.info/characters.html
You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:
const start = /[/]/g;
"/dev/null".match(start) // => ["/", "/"]
const word = /[/](\w+)/ig;
"/dev/null".match(word) // => ["/dev", "/null"]
I encountered two issues related to the foregoing, when extracting text delimited by \ and /, and found a solution that fits both, other than using new RegExp, which requires \\\\ at the start. These findings are in Chrome and IE11.
The regular expression
/\\(.*)\//g
does not work. I think the // is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)
/\b/\\(.*)\/\b/g
does not work either. I think the second / terminates the regular expression in spite of the escape character.
What does work for me is to represent / as \x2F, which is the hexadecimal representation of /. I think that's more efficient and understandable than using new RegExp, but of course it needs a comment to identify the hex code.
Forward Slash is special character so,you have to add a backslash before forward slash to make it work
$patterm = "/[0-9]{2}+(?:-|.|\/)+[a-zA-Z]{3}+(?:-|.|\/)+[0-9]{4}/";
where / represents search for /
In this way you
For me, I was trying to match on the / in a date in C#. I did it just by using (\/):
string pattern = "([0-9])([0-9])?(\/)([0-9])([0-9])?(\/)(\d{4})";
string text = "Start Date: 4/1/2018";
Match m = Regex.Match(text, pattern);
if (m.Success)
{
Console.WriteLine(match.Groups[0].Value); // 4/1/2018
}
else
{
Console.WriteLine("Not Found!");
}
JavaScript should also be able to similarly use (\/).

How to convert a C# regex to javascript? [duplicate]

I don't have much experience with JavaScript but i'm trying to create a tag system which, instead of using # or #, would use /.
var start = /#/ig; // # Match
var word = /#(\w+)/ig; //#abc Match
How could I use a / instead of the #. I've tried doing var slash = '/' and adding + slash +, but that failed.
You can escape it like this.
/\//ig; // Matches /
or just use indexOf
if(str.indexOf("/") > -1)
You need to escape the / with a \.
/\//ig // matches /
You can escape it by preceding it with a \ (making it \/), or you could use new RegExp('/') to avoid escaping the regex.
See example in JSFiddle.
'/'.match(/\//) // matches /
'/'.match(new RegExp('/') // matches /
If you want to use / you need to escape it with a \
var word = /\/(\w+)/ig;
In regular expressions, "/" is a special character which needs to be escaped (AKA flagged by placing a \ before it thus negating any specialized function it might serve).
Here's what you need:
var word = /\/(\w+)/ig; // /abc Match
Read up on RegEx special characters here: http://www.regular-expressions.info/characters.html
You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:
const start = /[/]/g;
"/dev/null".match(start) // => ["/", "/"]
const word = /[/](\w+)/ig;
"/dev/null".match(word) // => ["/dev", "/null"]
I encountered two issues related to the foregoing, when extracting text delimited by \ and /, and found a solution that fits both, other than using new RegExp, which requires \\\\ at the start. These findings are in Chrome and IE11.
The regular expression
/\\(.*)\//g
does not work. I think the // is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)
/\b/\\(.*)\/\b/g
does not work either. I think the second / terminates the regular expression in spite of the escape character.
What does work for me is to represent / as \x2F, which is the hexadecimal representation of /. I think that's more efficient and understandable than using new RegExp, but of course it needs a comment to identify the hex code.
Forward Slash is special character so,you have to add a backslash before forward slash to make it work
$patterm = "/[0-9]{2}+(?:-|.|\/)+[a-zA-Z]{3}+(?:-|.|\/)+[0-9]{4}/";
where / represents search for /
In this way you
For me, I was trying to match on the / in a date in C#. I did it just by using (\/):
string pattern = "([0-9])([0-9])?(\/)([0-9])([0-9])?(\/)(\d{4})";
string text = "Start Date: 4/1/2018";
Match m = Regex.Match(text, pattern);
if (m.Success)
{
Console.WriteLine(match.Groups[0].Value); // 4/1/2018
}
else
{
Console.WriteLine("Not Found!");
}
JavaScript should also be able to similarly use (\/).

Matching a Forward Slash with a regex

I don't have much experience with JavaScript but i'm trying to create a tag system which, instead of using # or #, would use /.
var start = /#/ig; // # Match
var word = /#(\w+)/ig; //#abc Match
How could I use a / instead of the #. I've tried doing var slash = '/' and adding + slash +, but that failed.
You can escape it like this.
/\//ig; // Matches /
or just use indexOf
if(str.indexOf("/") > -1)
You need to escape the / with a \.
/\//ig // matches /
You can escape it by preceding it with a \ (making it \/), or you could use new RegExp('/') to avoid escaping the regex.
See example in JSFiddle.
'/'.match(/\//) // matches /
'/'.match(new RegExp('/') // matches /
If you want to use / you need to escape it with a \
var word = /\/(\w+)/ig;
In regular expressions, "/" is a special character which needs to be escaped (AKA flagged by placing a \ before it thus negating any specialized function it might serve).
Here's what you need:
var word = /\/(\w+)/ig; // /abc Match
Read up on RegEx special characters here: http://www.regular-expressions.info/characters.html
You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:
const start = /[/]/g;
"/dev/null".match(start) // => ["/", "/"]
const word = /[/](\w+)/ig;
"/dev/null".match(word) // => ["/dev", "/null"]
I encountered two issues related to the foregoing, when extracting text delimited by \ and /, and found a solution that fits both, other than using new RegExp, which requires \\\\ at the start. These findings are in Chrome and IE11.
The regular expression
/\\(.*)\//g
does not work. I think the // is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)
/\b/\\(.*)\/\b/g
does not work either. I think the second / terminates the regular expression in spite of the escape character.
What does work for me is to represent / as \x2F, which is the hexadecimal representation of /. I think that's more efficient and understandable than using new RegExp, but of course it needs a comment to identify the hex code.
Forward Slash is special character so,you have to add a backslash before forward slash to make it work
$patterm = "/[0-9]{2}+(?:-|.|\/)+[a-zA-Z]{3}+(?:-|.|\/)+[0-9]{4}/";
where / represents search for /
In this way you
For me, I was trying to match on the / in a date in C#. I did it just by using (\/):
string pattern = "([0-9])([0-9])?(\/)([0-9])([0-9])?(\/)(\d{4})";
string text = "Start Date: 4/1/2018";
Match m = Regex.Match(text, pattern);
if (m.Success)
{
Console.WriteLine(match.Groups[0].Value); // 4/1/2018
}
else
{
Console.WriteLine("Not Found!");
}
JavaScript should also be able to similarly use (\/).

Javascript: String replace problem

I've got a string which contains q="AWORD" and I want to replace q="AWORD" with q="THEWORD". However, I don't know what AWORD is.. is it possible to combine a string and a regex to allow me to replace the parameter without knowing it's value? This is what I've got thus far...
globalparam.replace('q="/+./"', 'q="AWORD"');
What you have is just a string, not a regular expression. I think this is what you want:
globalparam.replace(/q=".+?"/, 'q="THEWORD"');
I don't know how you got the idea why you have to "combine" a string and a regular expression, but a regex does not need to exist of wildcards only. A regex is like a pattern that can contain wildcards but otherwise will try to match the exact characters given.
The expression shown above works as follows:
q=": Match the characters q, = and ".
.+?": Match any character (.) up to (and including) the next ". There must be at least one character (+) and the match is non-greedy (?), meaning it tries to match as few characters as possible. Otherwise, if you used .+", it would match all characters up to the last quotation mark in the string.
Learn more about regular expressions.
Felix's answer will give you the solution, but if you actually want to construct a regular expression using a string you can do it this way:
var fullstring = 'q="AWORD"';
var sampleStrToFind = 'AWORD';
var mat = 'q="'+sampleStrToFind+'"';
var re = new RegExp(mat);
var newstr = fullstring.replace(re,'q="THEWORD"');
alert(newstr);
mat = the regex you are building, combining strings or whatever is needed.
re = RegExp constructor, if you wanted to do global, case sensitivity, etc do it here.
The last line is string.replace(RegExp,replacement);

regex and javascript

using http://www.regular-expressions.info/javascriptexample.html I tested the following regex
^\\{1}([0-9])+
this is designed to match a backslash and then a number.
It works there
If I then try this directly in code
var reg = /^\\{1}([0-9])+/;
reg.exec("/123")
I get no matches!
What am I doing wrong?
Update:
Regarding the update of your question. Then the regex has to be:
var reg = /^\/(\d+)/;
You have to escape the slash inside the regex with \/.
The backslash needs to be escaped in the string too:
reg.exec("\\123")
Otherwise \1 will be treated as special character.
Btw, the regular expression can be simplified:
var reg = /^\\(\d+)/;
Note that I moved the quantifier + inside the capture group, otherwise it will only capture a single digit (namely 3) and not the whole number 123.
You need to escape the backslash in your string:
"\\123"
Also, for various implementation bugs, you may want to set reg.lastIndex = 0;.
In addition, {1} is completely redundant, you can simplify your regex to /^\\(\d)+/.
One last note: (\d)+ will only capture the last digit, you may want (\d+).

Categories