how do I change the regex to get the desired one? - javascript

I need to check a string where at the end the to symbols are mandatory, first is '#' and the second is given with the t variable.
I have got this:
var t = 0;
var p = /^[a-z0-9A-Z_-]*#$/ + t.toString();
p.test("asdf2#0");
and get always 'false'
how to add the t String to the RegExp of p variable
Now, I have searched a bit and found out that people do use RegExp constructor:
var t = 0;
var re = new RegExp("^\/\\[a-z0-9A-Z_-]*#" + t.toString() + "\/\\$");
var z = re.test("asdf2#0");
in this case z is always 'false'.
what I am doing wrong? Can you please, also explain what \ means exactly and why and where to apply it in the RegExp.

$ signals the end of the input string, so you need to add the variable value before it. To do so you must use the explicit Regexp object instead of the simplified version. Try the following:
var t = 0;
var p = new RegExp("^[a-z0-9A-Z_-]*#" + t + "$");

What are all the backslashes you have in that regex? I assume some of them are being interpreted as characters, and they aren't in your test string. If you remove them, it works just fine.

Related

RegEx match not working

So what I want to match is anything that ends with ".ProjectName" so I wrote a small test case. I purposely created the pattern using RegExp because in the real case scenario I will be using a variable as part of the reg ex pattern. I'm not sure if my pattern is not correct (90% sure it correct), or if I am misusing the match function (70% sure I am suing it right). The blow code returns me something when the second case notMatchName should not return me anything
var inputName = "ProjectName";
var matchName = "userInput_Heading.Heading.ProjectName";
var notMatchName = "userInput_Heading.Heading.Date";
var reg = new RegExp(".*[." + inputName + "]");
console.log(reg);
console.log(matchName.match(reg));
console.log(matchName.match(reg)[0]);
console.log(notMatchName.match(reg));
console.log(notMatchName.match(reg)[0]);
Here is the JsFiddle to help.
Use
var reg = new RegExp(".*\." + inputName);
The square brackets mean: one character, which is one of those within the brackets. But you want several characzters, first a dot, then the first character of inputName, etc.
your regular expression should be .*\.projectName
if you rewrite your statement it will be
var reg = new RegExp(".*\." + inputName)

Finding image url via using Regex

Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.

Javascript Regexp Duplicate Line Matching not working correctly

I am writing a Javascript code to parse some grammar files, it is quite some code but I will post relevant information here. I am using Javascript Regexp in order to match a duplicate line held within a string. The string contains, for example (assume the string name is lines):
if
else
;
print
{
}
test1
test1
=
+
-
*
/
(
)
num
string
comment
id
test2
test2
What should happen, is a match found on 'test1' and 'test2'. It should then delete the duplicate, leaving 1 instance of test1 and test2. What is happening is no match at all. I am confident in my regex but javascript may be doing something I am not expecting. Here is the code doing the work on the string given above:
var rex = new RegExp("(.*)(\r?\n\1)+","g");
var re = '/(.*)(\r?\n\1)+/g';
rex.lastIndex = 0;
var m = rex.exec(lines);
if (m) {
alert("Found Duplicate");
var linenum = lines.search(re); //Get line number of error
alert("Error: Symbol Defined twice\n");
alert("Error occured on line: " + linenum);
lines = lines.replace(rex,""); //Gets rid of the duplicate
}
It never gets into the if(m) statement. Therefore no match is found. I tested the regex here: http://regexpal.com/ using the regex in my code as well as the example text provided. It matches just fine, so I am at kind of a loss. If anyone can help, it would be great.
Thank you.
Edit:
Forgot to add, I am testing this in firefox, and it only has to work in firefox. Not sure if that matters.
First error: \ in a JS string is also an escape character.
var rex = new RegExp("(.*)(\r?\n\1)+","g");
should be written
var rex = new RegExp("(.*)(\\r?\\n\\1)+","g");
// or, shorter:
var rex = /(.*)(\r?\n\1)+/g;
if you want to make it work. In the case of the RegExp constructor, you’re passing the pattern as a string to the constructor function. This means you need to escape each \ backslash that occurs in the pattern. If you use a regexp literal, you don’t need to escape them, since they’re not in a string, but retain their ‘normal’ properties in the regexp pattern.
Second error, your expression
var re = '/(.*)(\r?\n\1)+/g';
is wrong. What you’re doing here is assigning a string literal to a variable. I’m assuming you meant to assign a regular expression literal, which should be written like this:
var re = /(.*)(\r?\n\1)+/g;
Third error: the last line
lines = lines.replace(rex,""); //Gets rid of the duplicate
removes both instances of all duplicate lines! If you want to keep the first instance of each duplicate, you should use
lines = lines.replace(rex, "$1");
And finally, this method only detects two consecutive identical lines. Is that what you want, or do you need to detect any duplicates, wherever they may be?
var str = 'if\nelse\n;\nprint\n{\n}\ntest1\ntest1\n=\n+\n-\n*\n/\n(\n)\nnum\nstring\ncomment\nid\ntest2\ntest2\ntest2\ntest2\ntest2';
console.log(str);
str = str.replace(/\r\n?/g,'');
// I prefer replacing all the newline characters with \n's here
str = str.replace(/(^|\n)([^\n]*)(\n\2)+/g,function(m0,m1,m2,m3,ind) {
var line = str.substr(0,ind).split(/\n/).length + 1;
var msg = '[Found duplicate]';
msg += '\nFollowing symbol defined more than once';
msg += '\n\tsymbol: ' + m2;
msg += '\n\ton line ' + line;
console.log(msg);
return m1 + m2;
});
console.log(str);
Otherwise you can skip the first line and change the pattern into
/(^|\r\n?|\n)([^\r\n]*)((?:\r\n?|\n)\2)+/g
Note that [^\n]* will also catch multiple empty lines. If you want to make sure it matches (and replaces) non-empty lines then you might want to use [^\n]+.
[EDIT]
For the record, each m represents each arguments object, so m0 is the whole match, m1 is the 1st subgroup ((^|\n)), m2 is the 2nd subgroup (([^\n]*)) and m3 is the last subgroup ((\n\2)). I could have used arguments[n] instead but these are shorter.
As with the return value, due to lack of lookbehind in the regex flavor used by Javascript, this pattern is catching a possible preceding newline (unless it is the first line) so it needs to return the match and that preceding newline if any. That's why it shouldn't be returning m2 only.

Passing regex modifier options to RegExp object

I am trying to create something similar to this:
var regexp_loc = /e/i;
except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn't get what i wanted.
Basically I want the e in the above regexp to be a string variable but I fail with the syntax.
I tried something like this:
var keyword = "something";
var test_regexp = new RegExp("/" + keyword + "/i");
Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.
regards,
alexander
You need to pass the second parameter:
var r = new RegExp(keyword, "i");
You will also need to escape any special characters in the string to prevent regex injection attacks.
You should also remember to watch out for escape characters within a string...
For example if you wished to detect for a single number \d{1} and you did this...
var pattern = "\d{1}";
var re = new RegExp(pattern);
re.exec("1"); // fail! :(
that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...
var pattern = "\\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);
re.exec("1"); // success! :D
When using the RegExp constructor, you don't need the slashes like you do when using a regexp literal. So:
new RegExp(keyword, "i");
Note that you pass in the flags in the second parameter. See here for more info.
Want to share an example here:
I want to replace a string like: hi[var1][var2] to hi[newVar][var2].
and var1 are dynamic generated in the page.
so I had to use:
var regex = new RegExp("\\\\["+var1+"\\\\]",'ig');
mystring.replace(regex,'[newVar]');
This works pretty good to me. in case anyone need this like me.
The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.
var keyword = "something";
var test_regexp = new RegExp(something,"i");
You need to convert RegExp, you actually can create a simple function to do it for you:
function toReg(str) {
if(!str || typeof str !== "string") {
return;
}
return new RegExp(str, "i");
}
and call it like:
toReg("something")

JavaScript replace()

I'm trying to use the replace function in JavaScript and have a question.
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(/_existing_0/gi,
"_existing_" + "newCounter");
That works.
But I need to have the "0" be a variable.
I've tried:
_ + myVariable +/gi and also tried
_ + 'myVariable' + /gi
Could someone lend a hand with the syntax for this, please. Thank you.
Use a RegExpobject:
var x = "0";
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(new RegExp("_existing_" + x, "gi"), "existing" + "newCounter");
You need to use a RegExp object. That'll let you use a string literal as the regex, which in turn will let you use variables.
Assuming you mean that you want the zero to be any single-digit number, this should work:
y = x.replace(/_existing_(?=[0-9])/gi, "existing" + "newCounter");
It looks like you're trying to actually build a regex literal with string concatenation - that won't work. You need to use the RegExp() constructor form instead, in order to inject a specific variable into the regex: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/RegExp
If you use the RegExp constructor, you can define your pattern using a string like this:
var myregexp = new RegExp(regexstring, "gims") //first param is pattern, 2nd is options
Since it's a string, you can do stuff like:
var myregexp = new RegExp("existing" + variableThatIsZero, "gims")

Categories