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);
Related
After reading this Question I am trying to use this regex
/(!<[^>]+>)+/g
Like this
var regex = /(!<[^>]+>)+/g;
new RegExp('myString', regex)
but I get
Uncaught SyntaxError: Invalid flags supplied to RegExp constructor
'/(!<[^>]+>)+/g'
Anybody have idea how to use it right?
new Regexp is used when you have a regular expression in a string and you want to convert it to a regular expression object.
It is awful and you should almost never use it. (The exception is when you are dynamically generating a regex).
You don't need to use it: You created the object using a regular expression literal on the previous line.
To apply the regular expression to a string, use the match method:
var regex = /(!<[^>]+>)+/g;
console.log("myString".match(regex));
console.log("Trivial !<tag> example".match(regex));
console.log("!<tag attribute='>>>'> example".match(regex));
(But applying regex to HTML is usually a terrible idea).
RegExp is used to create regular expression from string
The second attribute should be flags like i , g, m but you're giving a regular expression itself.
The syntax of RegExp is RegExp(regexString,flags)
but you are using
var regex = /(!<[^>]+>)+/g;
new RegExp('myString', regex)
^^^^^^
You can't use the RegExp function to test a string.
if you want to check 'myString' against your regular expression, use regex.test('myString')
if you want to find all matches of the regex in 'myString', use 'myString'.match(regex)
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.
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.
i m using regular expression to divide string data into specified number of blocks , everything works well in browser but when i try the same page in phonegap it doesn't work at all.
here is my code where blockString[1] contains the string data and resSize represents where to divide the string.
var pattern = "/.{1,"+resSize+"}/";
var rex = new RegExp(pattern,"g");
var finalBlocks = blockString[1].match(rex);
but finalBlocks always returns null in phonegap
following is the data which is a base64 representation of image , its a content of blockString[1]
iVBORw0KGgoAAAANSUhEUgAAAeAAAAMgCAIAAAB0wSZfAAAAA3NCSVQICAjb4U/gAAAgAElEQVR4nOy9WZccR5IuZot7RGRm7VUAsRIAu9mcmZ6+R+foQU960YP+uqQHHR3dq7mty2lON9kgCYDYasklwt3M9GDukZFVAIdQX/Y0m3QAhazIWD3cPzf/7DNz/F//5/9FVUVEVc3MzAAAABARAGxSmHm6EW6Ucbv/ZASs28efAIAIiDuX8J8iSVWZmYiml/AtvrOqAgARIaAOoln9thGBmUIIzOxnzTmLiJiqKU4KMyNSSsl3AIMYW6Lg5xExRGyaJgYmSKZps9mklMb7QcQYYwiBiAAgpaSqIQQAyDmbmd/qWMbH9F/HylRVVTHTaU3ibplW7DvPOa32a+cBBNit3un5p8eO5x93uLbn9AzblwiISAhYtk/O9s6iqllleqFyAwA2aQzjFREIjf38XmF+ESztBxGRyA8BACBCprGF2LgPIgKWOydERmJmZm5i07YtIfktEWGMsWmapmlijH6evt+sl8v1erVarZh5Nmtns9l8Po8hMGNKabPZ5JxSyt72iIiIvDclhV7B22BOKQ8p56yqpgZmvicTMRGh/8IUgt+nt+nSH2v9l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VjGkpyzw8LYa/zmc84bgT7DpJWXO0CDVPo8cvEPlqnYpHnA6H31E/r5zTEDERGPj4/ne6f7+4cHBweHR0eHx8fz+Xw2m1GIyNE7UWy2
First of all: you should remove the slashes within the pattern string unless your intention is to match expressions between two slashes. The RegExp constructor does not expect the pattern to be surrounded by slashes.
Despite that, it looks fine so I would guess that something is wrong with either blockString or resSize when you run the code on the device/emulator.
From the comments:
yeah it was my bad the problem was resSize was coming in a floating
number – Hunt
Does anyone know how to find regular expression string from javascript code?
e.g.
var pattern = /some regular expression/;
Is it possible to to with regular expression :) ?
If I got your question right, and you need a regular expression which would find all the regular expressions in a JavaScript program, then I don't think it is possible. A regular expression in JavaScript does not have to use the // syntax, it can be defined as a string. Even a full-blown JavaScript parser would not be smart enough to detect a regular expression here, for instance:
var re = "abcde";
var regexClass = function() { return RegExp; }
var regex = new regexClass()(re);
So I would give up this idea unless you want to cover only a few very basic cases.
You want a regex to match a regex? Crazy. This might cover the simplest cases.
new RegExp("\/.+\/")
However, I peeked into the Javascript Textmate bundle and is has 2 regex for finding a regex start and end.
begin = '(?<=[=(:]|^|return)\s*(/)(?![/*+{}?])'
end = '(/)[igm]*';
Which you could probably use as inspiration for toward your goal.
Thanks for answers I have found also that it is nearly impossible task to do, but here is my regex which parses source code just fine:
this.mainPattern = new RegExp(//single line comment
"(?://.*$)|"+
//multiline comment
"(/\\*.*?($|\\*/))"+
//single or double quote strings
"|(?:(?:\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|(?:'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'))"+
//regular expression literal in javascript code
"|(?:(?:[/].+[/])[img]?[\\s]?(?=[;]|[,]|[)]))"+
//brackets
"|([{]|[(]|[\[])|([}]|[)]|[\\]])", 'g');