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+nSH2v9lLqC8iwKpMB+qJmpmojknA3IwE9PBqQGOft20G3bQKNJQ6JtfSKh35AIimyb3Niq39m8EbHrutlsRkTMHGOMMbZt2zRN13Vt27Zt23Wd16130nbWtV2HRH5OIgohhBB8Bz9DCDGE6N9Or0X1qGvt2VufN8KsWU38ar7x9es3r1+9/uIPX/zbF3/44x//9OWXX65Xq81m0zRNCEFSyimXcwKMDQ8Bxjscu4ya5pyTpLH3XetiDln+pH6sA+y1zvU9/dEUELBpmvCP//iPUou3re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/PXmxGe68RrOTo+yYuFuKct3tPjdY98zhFynhieH4E0b/X0AbfUA2J3N+WWmNVPR0LHx2shR2eexCxvY1sJSq93Tr1WYTWYOjBWv0dleZgIkBIGsIpJy32/K1LVOzJkZEABKoxWxlCZ8NxNRAVXLxTjwO/Fje8VVtux9V7aUltVnVjOALUCjGkF5p2oFndUUANGKjU8IRAiAYCaCQzaAwDGGGGPbzmazxWLRzRbtfNF1Xde288X+fG9/sVgsFotuPm9n80IyBKbAEwt6/By5ArQZAlB9P4AAamCGWkCkvBfn+8Vf7jvQYvqSJ78CiEk2udkad7fs2hNbTg2vTT0BwcbXDwAAZEiGgAFDGb+TwSBgPmMHAm66/W5+iESAYCBgCoRQfRbbgb+6PaBy3KBqfRr6PEy5aW8/znIgIjO1bde2TdtSCCiClWspjzL9WywMLScHgBlDJOj7HPq+n9YCVmZkNIjGLjrpPDYC0DX4mH6NFaBhp9P6l3IDuCWlJJId8tyDV/x41bo0n32aAgAYWELIZe4smt0AH40d9+GcX56fX5Ty9u3bt2/feg0eHBzcv3//t7/97ZMnn7TtPHBMKeecU8r9pr+4uFhevk3Ll29ffvP5558/ffq07/v1em1mbiz7eOZXugle16oFJk8OW8u0PNDNBjoi+GhTX3sR1wzhm/uUY3eogO/D6Js3Od1zes7JPmjF4rxuaF+77XJ1RKxNeXoVJ6tGCxpHR4ICWmm5BcIQAaCydkBEPgeu/ZYQFXCc3hYWE+rbKUZDdeKRAWR1eCSitm1HayPnnFICACR0LpuI/ATVGVjGkpyzw8LYa/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
Related
I am attempting to generate some code using escodegen's .generate() function which gives me a string.
Unfortunately it does not remove completely the semi-colons (only on blocks of code), which is what I need it to do get rid of them myself. So I am using the the .replace() function , however the semi-colons are not removed for some reason.
Here is what I currently have:
generatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions)
const cleanGeneratedCode = generatedFile.replace(';', '')
console.log('cleanGeneratedCode ', cleanGeneratedCode) // string stays the exact same.
Am I doing something wrong or missing something perhaps?
As per MDN, if you provide a substring instead of a regex
It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
So, the output probably isn't exactly the same as the code generated, but rather the first semicolon has been removed. To remedy this, simply use a regex with the "global" flag (g). An example:
const cleanGenereatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions).replace(/;/g, '');
console.log('Clean generated code: ', cleanGeneratedCode);
How do we do look behind in java script like we can in java or php?
RegEx works for php parser using lookbehind
Here is the working Regex using php parser.
(?<=MakeName=)(.*?)([^\s]+)
This produces the value
(MakeName=)(.*?)([^\s]+)
this produces the match + value
xml response to extract value from.
<ModelName="Tacoma" MakeName="Tundra" Year="2015">
I just need the value
There is no look-behind in JavaScript.
If you are sure the attribute MakeName is present in the input, then you could use this regular expression:
/[^"]*(?!.*\sMakeName\s*=)(?="([^"]*"[^"]*")*[^"]*$)/
It grabs the first series of characters that do not contain a double quote and have a double quote immediately following it, with an even number of double quotes following after that until the end of the input (to make sure we are matching inside a quoted string), but MakeName= should not occur anywhere after the match.
This is of course still not bullet proof, as it will fail for some boundary cases, like with single quoted values.:
<ModelName="Tacoma" MakeName='Tundra' Year="2015">
You could resolve that, if needed, by repeating the same pattern, but then based on single quotes, and combining the two with an OR (|).
Demo:
var s = '<ModelName="Tacoma" MakeName="Tundra" Year="2015">';
result = s.match(/[^"]*(?!.*\sMakeName\s*=)(?="([^"]*"[^"]*")*[^"]*$)/);
console.log(result[0]);
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 have a JS file with some XML in it, where the XML is supposed to get converted to a word by the server.
E.g.
var ip = "<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>";
This gets converted to:
var ip = "192.168.0.0";
However, in case the server doesn't work as intended, I don't want there to be a syntax error, and this is VERY important. Currently there would be a syntax error because the language uses both types of quotes. I can't think of a way to get around this, but perhaps there's another way to do quotes in JavaScript? Or to create a string?
For example, in Python I'd use triple quotes:
ip = """<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>"""
Anyone have a bright idea?
I have had to create strings without quotes for a project as well. We were delivering executable client javascript to the browser for an internal website. The receiving end strips double and single quotes when displayed. One way I have found to get around quotes is by declaring my string as a regular expression.
var x = String(/This contains no quotes/);
x = x.substring(1, x.length-1);
x;
Using String prototype:
String(/This contains no quotes/).substring(1).slice(0,-1)
Using String.fromCharCode
String.fromCharCode(72,69,76,76,79)
Generate Char Codes for this:
var s = "This contains no quotes";
var result = [];
for (i=0; i<s.length; i++)
{
result.push(s.charCodeAt(i));
}
result
In JavaScript, you can escape either type of quote with a \.
For example:
var str = "This is a string with \"embedded\" quotes.";
var str2 = 'This is a string with \'embedded\' quotes.';
In particular, your block of JavaScript code should be converted to:
var ip = "<lang:cond><lang:when test=\"$(VAR{'ip_addr'})\">$(VAR{'ip_addr'})</lang:when></lang:cond>";
In general, I always prefer to escape the quotes instead of having to constantly switch quote types, depending upon what type of quotes may be used within.
I was looking for a solution to the same problem. Someone suggested looking at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings which proved helpful. After reading about half the article, it stated that you can create strings with the backward tick character. (`)
Try this :)
document.getElementById('test').innerHTML = `'|'|'|"|"`
<div id="test" style="font-size:3em;"></div>
You can't create a string without using a single or double quote, as even calling the String() prototype object directly still requires you to pass it the string.
Inside XML you would use CDATA, but inside JS you'll have to just escape the '\"strings\"' "\'appropriately\'"
I am generating XML using Javascript. It works fine if there are no special characters in the XML. Otherwise, it will generate this message: "invalid xml".
I tried to replace some special characters, like:
xmlData=xmlData.replaceAll(">",">");
xmlData=xmlData.replaceAll("&","&");
//but it doesn't work.
For example:
<category label='ARR Builders & Developers'>
Thanks.
Consider generating the XML using DOM methods. For example:
var c = document.createElement("category");
c.setAttribute("label", "ARR Builders & Developers");
var s = new XMLSerializer().serializeToString(c);
s; // => "<category label=\"ARR Builder & Developers\"></category>"
This strategy should avoid the XML entity escaping problems you mention but might have some cross-browser issues.
This will do the replacement in JavaScript:
xml = xml.replace(/</g, "<");
xml = xml.replace(/>/g, ">");
This uses regular expression literals to replace all less than and greater than symbols with their escaped equivalent.
JavaScript comes with a powerful replace() method for string objects.
In general - and basic - terms, it works this way:
var myString = yourString.replace([regular expression or simple string], [replacement string]);
The first argument to .replace() method is the portion of the original string that you wish to replace. It can be represented by either a plain string object (even literal) or a regular expression.
The regular expression is obviously the most powerful way to select a substring.
The second argument is the string object (even literal) that you want to provide as a replacement.
In your case, the replacement operation should look as follows:
xmlData=xmlData.replace(/&/g,"&");
xmlData=xmlData.replace(/>/g,">");
//this time it should work.
Notice the first replacement operation is the ampersand, as if you should try to replace it later you would screw up pre-existing well-quoted entities for sure, just as ">".
In addition, pay attention to the regex 'g' flag, as with it the replacement will take place all throughout your text, not only on the first match.
I used regular expressions, but for simple replacements like these also plain strings would be a perfect fit.
You can find a complete reference for String.replace() here.