alert(window.location.href/&name=" + escape(name_var) + "&id=" + escape(id_var));
thanks
No, it's not correct.
alert(window.location.href + "&name=" + encodeURIComponent(name_var) + "&id=" + encodeURIComponent(id_var));
You have a syntax error in your code, the / that follows window.location.href
Use the concatenation operator, + - myString + "more string"
escape is deprecated, use encodeURI() and encodeURIComponent()
Related
I want to encode a string to UTF-8 in JavaScript. In java we use URLEncoder.encode("String", "UTF-8") to achieve this.
I know we can use encodeURI or encodeURIComponent but it is producing different output than URLEncoder.encode
Can anyone please suggest any available JS method that can be used to achieve same output as URLEncoder.encode.
NOTE:
Due to restrictions I cannot use jQuery.
I don't know if this javaURLEncode() function is a spot-on match for Java's URLEncoder.encode method, but it might be close to what you're looking for:
function javaURLEncode(str) {
return encodeURI(str)
.replace(/%20/g, "+")
.replace(/!/g, "%21")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/~/g, "%7E");
}
var testString = "It's ~ (crazy)!";
var jsEscape = escape(testString);
var jsEncodeURI = encodeURI(testString);
var jsEncodeURIComponent = encodeURIComponent(testString);
var javaURLEncoder = javaURLEncode(testString);
alert("Original: " + testString + "\n" +
"JS escape: " + jsEscape + "\n" +
"JS encodeURI: " + jsEncodeURI + "\n" +
"JS encodeURIComponent: " + jsEncodeURIComponent + "\n" +
"Java URLEncoder.encode: " + javaURLEncoder);
found one more character should be replaced
.replace(/\$/g, "%24")
I am currently learning a little bit of JavaScript and had a question.
In PHP, I am used to binding text and strings together with a simple dot like this:
echo "Text" . $String . "anotherText" . $anotherString
Is this possible in JavaScript? (Not the echo, but the binding of the strings and text.)
The + is the concatenation operator in JavaScript:
"Text" + somestring + "anotherText" + anotherString;
In JavaScript it's + instead of .
Example 1:
document.write("Text" + somestring + "anotherText" + anotherString);
Example 2:
alert("Text" + somestring + "anotherText" + anotherString);
Example 3:
var john = "Text" + somestring + "anotherText" + anotherString;
Yes just, add:
'Text' + str + 'anotherText' + anotherString;
I am attempting to call a JavaScript function from jQuery. When I try to pass an argument to JavaScript function:
var brandRcObj = "b-brand-box";
$('.b-brand-box').on('mouseleave', function(){
brandOn(brandRcObj);
});
I am getting the following error:
"Uncaught Error: Syntax error, unrecognized expression: '.b-brand-box'"
I'm doing this because I will use the same mouseleave event multiple times in my project. Therefore I wanted to write a JavaScript function as follows:
function brandOn(brandClass){
var classObj = "'" + "." + brandClass + "'";
var imgObj = "'" + "." + brandClass + " " + "img" + "'";
$(classObj).css({
backgroundColor: 'white',
opacity: 1
});
$(imgObj).css({
opacity: 1
});
}
Thanks for yor help!
'.b-brand-box' is not a valid class selector – .b-brand-box is.
You are putting single quotes around the value you are dynamically generating, although there should not be any – you are mistaking the notation of a text literal in JavaScript syntax for its actual string value.
'.b-brand-box' is the notation of a text literal in JavaScript code, ".b-brand-box" would be another valid way of writing it. The value of both of those strings after the source code has been parsed is only .b-brand-box however.
What you actually want is just simply
"." + brandClass;
and nothing more.
You do not need all those quotes, where you have:
var classObj = "'" + "." + brandClass + "'";
var imgObj = "'" + "." + brandClass + " " + "img" + "'";
all you need is
var classObj = "." + brandClass;
var imgObj = "." + brandClass + " " + "img";
The interpreter knows you have a string
I want to send http request using node.js. I do:
http = require('http');
var options = {
host: 'www.mainsms.ru',
path: '/api/mainsms/message/send?project='+project+'&sender='+sender+'&message='+message+'&recipients='+from+'&sign='+sign
};
http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
}).on('error', function(e) {
console.log('ERROR: ' + e.message);
});
When my path like this:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester_response&recipients=79089145***&sign=2c4135e0f84d2c535846db17b1cec3c6
Its work. But when message parameter contains any spaces for example tester response all broke. And in console i see that http use this url:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester
How to send spaces. Or i just can't use spaces in url?
What you are looking for is called URL component encoding.
path: '/api/mainsms/message/send?project=' + project +
'&sender=' + sender +
'&message=' + message +
'&recipients=' + from +
'&sign=' + sign
has to be changed to
path: '/api/mainsms/message/send?project=' + encodeURIComponent(project) +
'&sender=' + encodeURIComponent(sender) +
'&message=' + encodeURIComponent(message) +
'&recipients='+encodeURIComponent(from) +
'&sign=' + encodeURIComponent(sign)
Note:
There are two functions available. encodeURI and encodeURIComponent. You need to use encodeURI when you have to encode the entire URL and encodeURIComponent when the query string parameters have to be encoded, like in this case. Please read this answer for extensive explanation.
The question is for Node.js. encodeURIcomponent is not defined in Node.js. Use the querystring.escape() method instead.
var qs = require('querystring');
qs.escape(stringToBeEscaped);
The best way is to use the native module QueryString :
var qs = require('querystring');
console.log(qs.escape('Hello $ é " \' & ='));
// 'Hello%20%24%20%C3%A9%20%22%20\'%20%26%20%3D'
This is a native module, so you don't have to npm install anything.
TLDR: Use fixedEncodeURI() and fixedEncodeURIComponent()
MDN encodeURI() Documentation...
function fixedEncodeURI(str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
MDN encodeURIComponent() Documentation...
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
Why to Not Use encodeURI() and encodeURIComponent()
It is really not recommended to use encodeURI() and encodeURIComponent(), as they are insufficient to properly handle URI or URL encoding directly. Just like at this piece...
'&message=' + encodeURIComponent(message) +
Let's say that the message var is set to this: "Hello, world! (Really hello!)". So what is that evaluated to?
console.log('&message=' + encodeURIComponent("Hello, world! (Really hello!)"));
Output:
&message=Hello%2C%20world!%20(Really%20hello!)
That's not right! Why weren't ( and ) encoded? After all, according to RFC3986, Section 2.2: Reserved Characters...
If data for a URI component would conflict with a reserved character's purpose as a delimiter, then the conflicting data must be percent-encoded before the URI is formed.
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
Parens are a sub-delim, but they are not being escaped by encodeURI() or encodeURIComponent().
i++;
$("#test").html("<iframe id='i' src='arr[0]'></iframe>");
I want to assign the value of the array to the iframe source as shown here. This doesn't work however. How is this possible? Thanks
$("#test").html("<iframe id='" + i + "' src='" + arr[0] + "'></iframe>");
You need to use concatenation:
$("#test").html("<iframe id=\"" + i + "\" src=\"" + arr[0] + "\"></iframe>");
Edited to match updated question
Why your code doesn't work as expected:
$("#test").html("<iframe id='i' src='arr[0]'></iframe>");
generates the html output:
<div id="test">
<iframe id='i' src='arr[0]'></iframe>
</div>
Your variables are in fact outputted as literals, since you're not using any escaping/concatenation (see this article for JS string 101).
What you can do to make it work:
While the other answers are correct, consistently using single quotes for strings makes HTML concatenation way more fun (as attribute values should usually be in double quotes):
i++;
$("#test").html('<iframe id="' + i + '" src="' + arr[0] + '"></iframe>');
What you can do to make it work even more hassle-free for you:
It might be overkill if you need to concatenate just once. In the long run though, this approach by #Zippoxer makes your life much easier when you have to insert values into strings:
String.prototype.format = function() {
var formatted = this;
for(arg in arguments) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
Usage in your case:
$("#test").html('<iframe id="{0}" src="{1}"></iframe>'.format(i, arr[0]));
try this...
$("#test").html("<iframe id='" + i + "' src='" + arr[0] + "'></iframe>");
What you are doing with $("#test").html("<iframe id='i' src='arr[0]'></iframe>"); is setting the id to the literal character "i" and setting the src to the literal string "arr[0]" rather than the values of these variables.