Javascript storing regex in a variable - javascript

I have this line of code in javascript
var re = (http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])?
Usually I encapsulate the regex syntax with the / characters but since they are found within the regex it screws up the encapsulation. Is there another way how I can store it inside the variable?
The current slashes that seem like escape characters are part of the regex, since I am using this in c# aswell and works perfectly

var re = new RegExp("^your regexp.*$", "gi");

One way is to escape all occurances of / in your regex as \/, like you're already partially doing:
var re = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:\/~\+#]*[\w\-\#?^=%&\/~\+#])?/;

You can escape the slash inside your regex:
/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:\/~\+#]*[\w\-\#?^=%&\/~\+#])?/
(you already did so with the first two slashes...)

Related

Need help to use regex in match function of javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 5 years ago.
I am using a regex for getting some pattern data and it is working fine but I need to use some part of regex from a variable but I am unable to do that please help me if somebody know how to make it.
var subStr = document_root.documentElement.outerHTML.match(/http(.*?Frover.fff.com.*?)\;/g);
alert(subStr[0]);
I get first result in alert but need to do it like this.
var link=rover.fff.com;
var regexpattern="/http(.*?F"+link+".*?)\;/g"
var rex=new RegExp(regexpattern);
var subStr = document_root.documentElement.outerHTML.match(regexpattern);
alert(subStr[0]);
I don't get anything.
Please help me.
Comment if you confuse in anything.
In JavaScript, when you need to use a variable, you have to create a new RegExp object, as you've tried.
It takes two parameters. The first is a string of the pattern (without the slashes at the start and end). The second is any flags (like your g).
So, your pattern would be something like this:
var regexpattern = new RegExp('http(.*?F' + link + '.*?)\\;', 'g')
Note, that you have to escape any special characters in the string like you would any other string (in this case, your \ had to be escaped to \\ so it'll work properly).
After that, you use it the same as the /pattern/ form. In your case, be sure to use rex, not regexpattern in your match() function.
(If so some reason that wasn't a literal \ and you were escaping the semi-colon, just remove it completely, you won't need to escape a semi-colon.)

dynamically creating a regex with forward slashes in javascript

Im trying to match lines that have this format. Writing a static regEx is fine but I need to do this using 2 variables to create the regex dynamically.
I cant seem to get how to escape the forward brackets properly ive tried escaping them, not escaping them and even double escaping them (just for the heck of it) but fireBug shows the actual regEx being created the same no mater how I do itand it doesnt match my input.
Lines to match look like this:
9.SSRDOCSWSHK1/////23NOV96/M//YEUNG/WINSTON/JEREMY-5.1
What Ive tried:
var regString ='\\d{1,2}.SSRDOCS[0-9A-Z]{2}HK1[/]{5}\\d\\d[A-Z]{3}\\d\\d/[MF]//'+curGstNme+'([/A-Z]+)?-'+pax.slice(0,1)+'\.'
var namedGdocRegEx = new RegExp(regString,"g");
FireBug gives RegExp /\d{1,2}.SSRDOCS[0-9A-Z]{2}HK1[\/]{5}\d\d[A-Z]{3}\d\d\/[MF]\/\/CASTANEDA\/HAZEL([\/A-Z]+)?-1./g
---------------------------
var regString ='\\d{1,2}.SSRDOCS[0-9A-Z]{2}HK1[\/]{5}\\d\\d[A-Z]{3}\\d\\d\/[MF]\/\/'+curGstNme+'([\/A-Z]+)?-'+pax.slice(0,1)+'\.'
var namedGdocRegEx = new RegExp(regString,"g");
FireBug gives RegExp /\d{1,2}.SSRDOCS[0-9A-Z]{2}HK1[\/]{5}\d\d[A-Z]{3}\d\d\/[MF]\/\/CASTANEDA\/HAZEL([\/A-Z]+)?-1./g
---------------------------
var regString ='\\d{1,2}.SSRDOCS[0-9A-Z]{2}HK1[\\/]{5}\\d\\d[A-Z]{3}\\d\\d\\/[MF]\\/\\/'+curGstNme+'([\\/A-Z]+)?-'+pax.slice(0,1)+'\.'
var namedGdocRegEx = new RegExp(regString,"g");
FireBug gives RegExp /\d{1,2}.SSRDOCS[0-9A-Z]{2}HK1[\/]{5}\d\d[A-Z]{3}\d\d\/[MF]\/\/CASTANEDA\/HAZEL([\/A-Z]+)?-1./g
In regex you need to escape the DOTs since DOT will mean any character.
Use this regex:
regString ='\\d{1,2}\\.SSRDOCS[0-9A-Z]{2}HK1/{5}\\d\\d[A-Z]{3}\\d\\d/[MF]//'+ curGstNme + '([/A-Z]+)?-' + pax.slice(0,1) + '\\.';
Actually the problem was elsewhere. Apparently fireBug just shows the created regex (in the "watch" panel) with the escaping sashes visible. This made me think the regex was not being created correctly.
Your regex could be reduced like this:
var regString ='\\d{1,2}\\.SSRDOCS[0-9A-Z]{2}HK1/{5}\\d{2}[A-Z]{3}\\d{2}/[MF]//'+curGstNme+'([/A-Z]+)?-'+pax.slice(0,1)+'\.'
What did I change ?
\\d\\d can be replaced efficiently with \d{2}.
. replaced with \\. for matching exactly dot.
[/]{5} replaced by /{5}
This visually gives you:

Javascript Replace via RegEx

I am trying to replace 3 chars with 3 other chars to build/mask an email address for a form.
This works only once or on the first instance of finding it:
email = "email1#domain!com|email2#domain!com|email3#domain!com";
email.replace("#","#").replace("!",".").replace("|",",");
The above code resulted in: email1#domain.com,email2#domain!com|email3#domain!com
After some reading I read about using RegEx which is the portion of coding I can never wrap my head around:
email.replace("/#/g","#").replace("/!/g",".").replace("/|/g",",");
That didn't work either and left it the same as the original var.
What am I doing wrong?
Do not put quotes around the regex. Regexes are literals that use / as a boundary.
Additionally, you will need to escape the | because it has a special meaning.
Finally, .replace is not transformative. It returns the result.
email = email.replace(/#/g,'#').replace(/!/g,'.').replace(/\|/g,',');
Using regex literals, you omit the quotes (and you'll need to escape the pipe):
email.replace(/#/g,"#").replace(/!/g,".").replace(/\|/g,",");
email = "email1#domain!com|email2#domain!com|email3#domain!com";
email=email.replace(/#/g,"#").replace(/!/g,".").replace(/\|/g,",");

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

Say I have a string variable (var str) as follows-
Dude, he totally said that "You Rock!"
Now If I'm to make it look like as follows-
Dude, he totally said that "You Rock!"
How do I accomplish this using the JavaScript replace() function?
str.replace("\"","\\""); is not working so well. It gives unterminated string literal error.
Now, if the above sentence were to be stored in a SQL database, say in MySQL as a LONGTEXT (or any other VARCHAR-ish) datatype, what else string optimizations I need to perform?
Quotes and commas are not very friendly with query strings. I'd appreciate a few suggestions on that matter as well.
You need to use a global regular expression for this. Try it this way:
str.replace(/"/g, '\\"');
Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g (global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.
To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:
var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);

Why doesn't this particular regex work in JavaScript?

I have this regex on Javascript :
var myString="aaa#aaa.com";
var mailValidator = new RegExp("\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (!mailValidator.test(myString))
{
alert("incorrect");
}
but it shouldn't alert "incorrect" with aaa#aaa.com.
It should return "incorrect" for aaaaaa.com instead (as example).
Where am I wrong?
When you create a regex from a string, you have to take into account the fact that the parser will strip out backslashes from the string before it has a chance to be parsed as a regex.
Thus, by the time the RegExp() constructor gets to work, all the \w tokens have already been changed to just plain "w" in the string constant. You can either double the backslashes so the string parse will leave just one, or you can use the native regex constant syntax instead.
It works if you do this:
var mailValidator = /\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
What happens in yours is that you need to double escape the backslash because they're inside a string, like "\\w+([-+.]\\w+)*...etc
Here's a link that explains it (in the "How to Use The JavaScript RegExp Object" section).
Try var mailValidator = new RegExp("\\w+([-+.]\\w+)*#\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

Categories

Resources