Getting Javascript Regular Expression from Page - javascript

I'm trying to grab a regular expression from an HTML element so that I can use it for evaluation later, but for some reason when I grab the RE from the DOM it's different than when I statically define it in my Javascript. Here is my testing code:
<p id="test">\\b31\\b</p>
<script>
var j = document.getElementById('test').innerHTML;
console.log(j);
var i = "\\b31\\b"
console.log(i);
</script>
The results of this are \\b31\\b for j and \b31\b for i. Why isn't j also \b31\b? More importantly, how do I fix this? Because my regular expression evaluation later won't work with j, and I need to be able to grab regular expressions from the page to evaluate later, but right now I can't unless I statically define them.

i don't know exactly why this is happening, but you could just simply fix this with:
var j = document.getElementById('test').innerHTML.replace(/\\\\/g,"\\");
see example here:
https://jsfiddle.net/wjnm15gL/1/

You cannot "fix" this. By design, the backslash in JS is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.
If you want to use two backslashes, use four:
console.log('\\\\'); //returns \\

JavaScript strings automatically escape special characters following a \ character. Try this in your console to see:
console.log('It\'s a wonderful day');
//It's a wonderful day
That's why your j and i variables log differently to the console.

Related

How to make replace() global in JavaScript

I know this question had been asked lot of time but i could not find solution. I have some smilies which each of them has code to be rendered as smiley using replace() , but I get syntax error, I don't know why and how to render my code :/ to smiley
txt = " Hi :/ ";
txt.replace("/\:/\/g","<img src='img/smiley.gif'>");
Your regular expression doesn't need to be in quotes. You should escape the correct / forward slash (you were escaping the wrong slash) and assign the replacement, since .replace doesn't modify the original string.
txt = " Hi :/ ";
txt = txt.replace(/:\//g,"<img src='img/smiley.gif'>");
Based on jonatjano's brilliant deduction, I think you should add a little more to the regular expression to avoid such calamities as interfering with URLs.
txt = txt.replace(/:\/(?!/)/g,"<img src='img/smiley.gif'>");
The above ensures that :// is not matched by doing a negative-lookahead.
There are two problems in the first argument of replace() it escapes the wrong characters and it uses a string that seems to contain a regex instead of a real RegExp.
The second line should read:
txt.replace(/:\//g,"<img src='img/smiley.gif'>");
/:\//g is the regex. The first and the last / are the RegExp delimiters, g is the "global" RegExp option (String.replace() needs a RegExp instead of a string to do a global replace).
The content of the regex is :/ (the string you want to find) but because / has a special meaning in a RegExp (see above), it needs to be escaped and it becomes :\/.

Javascript error: Invalid regular expression flags

So I have an error in my code that's saying Invalid regular expression flags. The line at fault is this one: ctx.drawImage(/Users/aUser/Desktop/NightSquare.png, 200, 200);, but aUser is replaced with my actual name (changed for privacy). I'm running on a mac and I think I know what the problem is (I didn't include MacIntosh HD), but I'm not sure. How do I fix this?
Additional notes: The /Users/ part of the code is highlighted in red in my text editor (the same color as a string).
Any thing in between / & / is treated as a regular expression in Javascript. There are 2 ways of creating regular expressions in JavaScript.
var myRegEx = new RegExp("pattern") ;
var myRegEx = /pattern/ ;
So using /Users/aUser/Desktop/NightSquare.png is actually leading to your code being interpreted as some regular expression creation which you do not intend.
Just make it a string literal( using "" or '') and it will be fine.
In case aUser is a variable ,use the following string concatenation-
"/Users/"+aUser+"/Desktop/NightSquare.png"
Strings need to be in quotes:
ctx.drawImage("/Users/aUser/Desktop/NightSquare.png", 200, 200);

How to make this youtube videoId parsing RegExp work in JS?

I'm trying to use this great RegEx presented here for grabbing a video id from any youtube type url:
parse youtube video id using preg_match
// getting our youtube url from an input field.
var yt_url = $('#yt_url').val();
var regexp = new RegExp('%(?:youtube(?:-nocookie)?\\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\\.be/)([^"&?/ ]{11})%','i');
var videoId = yt_url.match( regexp ) ;
console.log('vid: '+videoId);
My console is always giving me a null videoId though. Am I incorrectly escaping something in my regexp var? I added the a second backslash to escape the single backslashes already.
Scratching my head?
% are delimiters for the PHP you got the link from, Javascript does not expect delimiters when using new RegExp(). Also, it looks like \\. should probably be replaced with \. Try:
var regexp = new RegExp('(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})','i');
Also, you can create a regular expression literally by using Javascript's /.../ delimiters, but then you'll need to escape all of your /s:
var regexp = /(?:youtube(?:-nocookie)?\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\\.be\/)([^"&?\/ ]{11})/i;
Documentation
Update:
A quick update to address the comment on efficiency for literal expressions (/ab+c/) vs. constructors (new RegExp("ab+c")). The documentation says:
Regular expression literals provide compilation of the regular expression when the script is loaded. When the regular expression will remain constant, use this for better performance.
And:
Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Since your expression will always be static, I would say creating it literally (the second example) would be slightly faster since it is compiled when loaded (however, don't confuse this into thinking it won't be creating a RegExp object). This small difference is confirmed with a quick benchmark test.

Putting regular expressions in strings

I am trying to dynamically create a javascript file B using a javascript file A (written in Node.js) by writing a string from A to a .js file B. I want to use regular expressions in the javascript file B. This requires me to put the regex functions for B in a string in A. However, whenever I use the backslash (escape character), file A interprets the regex function immediately, instead of treating it as a string.
Some code to help in understanding my problem:
var mongodata = "Some String with square and curly brackets ]}{]]},]},}{}{{}},{[[][,][,";
mongodata = 'var mongodata = ' + mongodata + ';\n function setData(){mongodata = mongodata.replace(/\[ /g,"").replace(/\] \},/g,"</td></tr>").replace(/\] \}/g,"</td></tr>"); document.getElementById("mongodata").innerHTML = mongodata;}';
That mongodata string is intended to be used as the content of a dynamically created .js file.
I understand the wording of this question may be slightly confusing. Please let me know if more clarification is needed.
In your string, just like the \n character, all the other backslashed expressions are being evaluated, so you must escape the backslashes. In other words, write a RegExp that outputs a RegExp. The proper way of escaping the backslashes themselves is \\\ , but you might need to escape other characters as well to prevent their evaluation.
Perhaps I'm misunderstanding your problem, but maybe put the string being assigned to mongodata in escaped quotes:
var mongodata = "\'Some String with square and curly brackets ]}{]]},]},}{}{{}},{[[][,][,\'";
Bit of a lottery this one. I too don't quite understand your question.
You can escape all of the RegEx special characters (. * ? [ ] Etc). You can also dynamically create RegEx operators using:
var objRegEx = new RegExp( pattern, modifiers );
Like I say, lottery... stab in the dark...

RegExp for remove first and last char and turn ending double slashes into single

I have the following Javascript code to obtain the inner string from an RegExp:
Function.prototype.method = function (name,func){
this.prototype[name] = func;
return this;
};
RegExp.method('toRawString', function(){
return this.toString().replace(/^.(.*).$/,"$1");
});
The purpose of this, is to avoid in string double quoting. For example, if you have a Windows file path "C:\My Documents\My Folder\MyFile.file", you can use it like the following:
alert(/C:\My Documents\My Folder\MyFile.file/.toRawString());
However it is not working for ""C:\My Documents\My Folder\" since it causes syntax error. The only way to avoid it is to keep double quoting at the end of the string. Thus it will be written
alert(/C:\My Documents\My Folder\\/.toRawString());
The fact is any odd number of back slashes on the end of the string will be an error, so all ending back slashes must be double escaped. It will not be hard to use a multiple line small implementation, but are there any single RegExp solution?
NOTE
When using toRawString the RegExp object for this is usually NOT going to be used for any other purpose except for that method. I just want to use the syntax of RegExp to avoid double back slashes in source code. Unfortunately the ending double slashes cannot be easily avoid. I think another workaround is to force a space at the end but that is another question then.
UPDATE
I finally solved the "another question" and posted the code here.
OK, I get what you're trying to do! It's hacky : )
Try something like:
return this.toString().slice(1, -1).replace(/\\+$/, '\\')
Hope that helps.
If you want to include the double quotes in the string just wrap it with single quotes.
s = '"C:\\My Documents\\My Folder\\MyFile.file"'
console.log(s) // Output => "C:\My Documents\My Folder\MyFile.file"
This produces a syntax error:
/C:\My Documents\/
But that regular expression could be written correctly like this:
/C:\\My Documents\\/
Or like this:
new RegExp("C:\\\\My Documents\\\\")
I think your function is just fine and is returning a correct result. Regular expressions just can't end with an unpaired backslash. It's not that you're double escaping - you're just escaping the escape character.
This would produce an error too:
new RegExp("C:\\My Documents\\")
A regular expression like this, for instance, can't be written without a pair of backslashes:
/C:\\What/
Without the second backslash, \W would be interpreted as a special character escape sequence. So escaping the escape character isn't only necessary at the end. It's required anywhere it might be interpreted as the beginning of an escape sequences. For that reason, it might be a good rule of thumb to always use two backslashes to indicate a backslash literal in a regular expression.

Categories