Javascript string variable unquoted? - javascript

I am using the QuickBlox JavaScript API. Looking through their code, I found this line:
var URL_REGEXP = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;
It appears that it has declared a string variable that is a regular expression pattern. Then it goes ahead to use that variable thus:
return str.replace(URL_REGEXP, function(match) {
url = (/^[a-z]+:/i).test(match) ? match : 'http://' + match;
url_text = match;
return '' + escapeHTML(url_text) + '';
});
I am wondering how is this possible? The var declared in the first line should be a string, but it is unquoted. Shouldn't this be a syntax error?
I went ahead and tested this code on my browser, and it works! This mean's I've got some learning to do here... Can anyone explain how this variable is declared?
Additionally, I tried to run the same code on my friends computer, the Chrome debugger throws a syntax error on the variable declaration line (unexpected token '/'). I am using Chrome Version 36.0.1985.143 m, my friend is using the same thing, but on my computer, it all works fine, on my friends computer, the code stops at the first variable declaration because of "syntax error".
Is there some setting that is different?
Any help would be appreciated.
UPDATE
Thanks for the quick answers. I've come from a PHP background, so thought that all regular expressions has to be initialized as strings :P.
Anyone can reproduce the syntax error I'm getting on my friends computer? (It still happens after disabling all extensions). I can't reproduce it either, and that's what is frustrating me.
UPDATE 2
I have tested and my friends computer and looked through the source. It appear to be due to some encoding problems (I'm not sure what). The regular expression is shown like this:
var URL_REGEXP = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?芦禄鈥溾€濃€樷€橾))/gi;
(The characters at the end of the code is some random chinese characters, it seems).
How can I change the encoding to match his browser/system? (He is running on a Windows 7 Chinese simplified system).

It is not a String variable. It is a regular expression.
Calling var varname = /pattern/flags;
is effective to calling var varname = new RegExp("pattern", "flags");.
You can execute the following in any browser that supports a JavaScript console:
>>> var regex = /(?:[\w-]+\.)+[\w-]+/i
>>> regex.exec("google.com")
... ["google.com"]
>>> regex.exec("www.google.com")
... ["www.google.com"]
>>> regex.exec("ftp://ftp.google.com")
... ["ftp.google.com"]
>>> regex.exec("http://www.google.com")
Anyone can reproduce the syntax error I'm getting on my friends computer? (It still happens after disabling all extensions). I can't reproduce it either, and that's what is frustrating me.
According to RegExp - JavaScript documentation:
Regex literals was present in ECMAScript 1st Edition, implemented in JavaScript 1.1. Use an updated browser.

No, it shouldn't be a syntax error. In Javascript, RegExp objects are not strings, they are a distinct class of objects. /.../modifiers is the syntax for a RegExp literal.
I can't explain the syntax error you got on your friend's computer, it looks fine to me. I pasted it into the Javascript console and it was fine.

Related

RegEx in javascript freezes and never returns a value

I want to write a general pattern to be used in matching domain names with URLs. I have a case like the code below. The problem is that when I run the code, the browser freezes and I close it manually. The variable domain holds domain names which can be of the form: yahoo.com and also us.yahoo.com. The variable myString is a URL to be tested against the stored one. The test should be successful if the strings share the stored domain name, e.g. in the example below, the match will be -1 because the domain is google.co.uk while the string has: google.com. But I'm not getting -1 result. Instead, the program freezes. What could be the problem?
var domain="accounts.google.co.uk";
myString="https://accounts.google.com/ManageAccount";
var result=myString.search("(https:\/\/)(.*\.)*"+domain+"(\/.*)*(\/)*");
console.log(result);
EDIT:
Also tried:
var patt = new RegExp("(https:\/\/)(.*\.)*"+domain+"(\/.*)*(\/)*");
var result=patt.test(myString)
The same problem. The browser freezes and can't inspect code.
Since you're creating a RegExp from a string you need to escape the backslashes:
myString.search("(https:\\/\\/)(.*\\.)*"+domain+"(\\/.*)*(\\/)*")
I honestly don't know why it freezes instead of throwing an error or just failing to match properly.

Javascript syntax and HTML entities

I work on some crawler software of my own and one of my users just reported it will not work with code like this:
onclick="document.location.href = 'http://www.example.com/somepage.aspx'; return false;"
i.e. inside Javascript code use ' instead of ' to designate start end end of string
What surprises me is that browsers I have tested do not report any JavaScript syntax errors... And it seems to work when I click at it... I must be having a brain meltdown - is ' around a string really legitimate Javascript code?
is ' around a string really legitimate Javascript code?
No. The browser will decode the character references before evaluating the value as JavaScript.

Illegal character in javascript

I've been debugging this for hours already but really can't find the culprit of this illegal character. My javascript looks fine. This is my code.
this.PrintApplication = function Test$PrintApplication(ApplicationID, callback) {
$.post("/Application/PrintApplication/" + ApplicationID,
function (data) {
var result = eval(data);
if (result.error) {
DisplayPrompt("Error", result.message);
return;
}
else {
callback(result.data);
}
});
};
In firebug it shows.
In inspect in chrome and in console it redirects me in this line.
Any idea where is that illegal character is in my function?
It looks like you've got some unprintable characters in your source. Do you have a way of displaying those in your editor and deleting them? Deleting and retyping the line might fix it as well.
If that's not the case, maybe what you're trying to evaluate isn't JavaScript at all. You could be running that on an image or some kind of binary data.
Remember to be extra super careful when using eval on data that comes from an external source. If you can avoid doing it, avoid it.
This might be due to the reason that you have copied the code from web and simply pasted in your file. Try typing the same code to the file.
This error occurs due to UTF-8 characters.
This could happen if you normally type with different alphabets. For example the Γreek question mark ; is a different ASCII character from the English semi colon ;. If you use the first, you'll get exactly this error.
One solution is to copy paste your method to notepad and then back to your IDE.
This will often normalise and eliminate weird characters that might be hidden or undecipherable.

Regex working in C# but not in javascript

Can anyone help getting a piece of regex working in javascript please?
This is the regular expression:
storify.com\/*(?<code>[^"]*)
It works fine in C# but I can't get it working in js, I presume due to a delimiter issue but not sure which characters are causing the problem.
This is the js I'm trying but gives me and an "invalid quanitifier" error on the first line
var myregex = /storify.com\/*(?<code>[^"]*)/;
var storify = 'http://storify.com/DigitalFirst/ces-2013-five-things-you-missed-day-3';
var remoteid = storify.match(myregex);
console.log(remoteid);
Thanks in advance for anyone who can help get this working.
JavaScript regexes have no suport for named captures (?<xxx>...), that is why.
More details here (note: JavaScript is referred to as ECMA [262, to be precise]).

How can i use Unicode string key In Javascript Object?

I want to use unicode string in Object as key, something as:
var t = {"姓名": "naitong"};
it's ok , t["姓名"] return "naitong"
but
Object.keys({"姓名": "naitong"})
I got " ", a blank string
Anyone knowes why?
Editting:
I install firebug and try it in the console, it works.
Acctually i use mozrepl, so that i can editing and run javascript in emacs.
So This have something to do with mozrepl
I have confirm that mozrepl support only "7bit safe ASCII", to tranform unicode ,i have to json-encode it in emacs, as:
alert(Object.keys(JSON.parse("{\"\\u59d3\\u540d\":\"naitong\"}")))
This is my first question asked on stackoverflow, and i got quick resp.
Thank you all.
Works fine for me in the firebug console:
>>> Object.keys({"姓名": "naitong"})
["姓名"]
Maybe you are trying to display it on a page that uses a different charset which does not contain those symbols.

Categories

Resources