Concatenating with variables in a string - javascript

I'm just beginning my learning process and am stuck now on this one string. I've searched MDN, Google and Bing and not found any help.
My code instructions tell me to assign a variable, which I did. Then it wants me to test in console.log. I've done so, and when I do with spaces and punctuation, it gives me an error saying that it expected an identifier and instead saw '+'.
If I take the punctuation out I don't have an error, but no punctuation. If I take out the extra spaces as well as punctuation, I get a strange run-on sentence but no errors. I'm working this problem in Udacity, it is quiz 24 of lesson 2.
My code is:
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1. + " James and Julia are so " + adjective2. + " I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);

You need to add the dots as strings as well.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1 + "."
+ " James and Julia are so " + adjective2 + "."
+ " I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
The dot . has a special meaning in Javascript. It works as accessor for properties of an object.
Math.floor(1.5); // return the integer value of the given number
Read more here about property accessor.

Add . (dot) inside the double quoted part of string, not next to the variable.
It is a part of string, not a in-memory variable. And you are calling no function after that.
Below snippet works properly.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1 + ". James and Julia are so " + adjective2 + ". I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
Example of using dot to call a function. It is not required in this case since it is already a string.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1.toString() + ". James and Julia are so " + adjective2.toString() + ". I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);

Related

Replace keyword with a javascript expression

I have a string like hey! <input/>, Welcome in a template.
I need to replace every <input/> with the a JS expression this.input.
eg:
//Input
"hey! <input/>, Welcome";
Output should be:
"hey! " + this.input + ", Welcome";
I can do a replace on the string with " + this.input + " but the problem is what if <input/> at the start or the end?
What is the best way to handle this?
Edit:
I don't want the output to be a string. I want the output to be a valid JS expression.
Valid inputs:
1) "hey! <input/>, Welcome";
2) "<input/>, Welcome";
3) "Welcome <input/>"
Outputs:
1) "hey! " + this.input + ", Welcome";
2) this.input + ", Welcome";
3) "Welcome " + this.input;
As I wrote in comments above you can use:
var input = 'foo';
var str = "hey! <input/>, Welcome";
str = str.replace(/(.*?)<input\/>(.*)/, '$1' + this.input + '$2');
console.log(str);
//=> "hey! foo, Welcome"
"hey! <input/>, Welcome".replace(/<input\/>/, this.input);
EDIT:
John Reisig made a blog entry about making a minimal templating language parser in javascript. It's well written and may be a good starting point for your own templating language.

JavaScript equivalent to URLEncoder.encode("String", "UTF-8") of Java

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")

json.stringify() multile objects into 1 string

is it possible?
basically i'm a trying to achieve something like this
JSON.stringify("address=",Obj_address,Obj_city,Obj_state,Obj_zip)
after stringify
to become like
address= "Address city state zip"
in a string like fashion. Reason being is I'm trying to pass this string into my google geocoding url api.
I played around and it so far only 1 parameter can be passed.
Help appreciated and thanks
This would be better.
var str = 'address="'+[Obj_address,Obj_city,Obj_state,Obj_zip].join(' ')+'"';
But you probaby don't need the quotes.
var str = 'address='+encodeURIComponent(
[Obj_address,Obj_city,Obj_state,Obj_zip].join(' '));
Or according to the api with a plus separator.
var str = 'address='+encodeURIComponent(
[Obj_address,Obj_city,Obj_state,Obj_zip].join('+'));
You need to try like this one
alert("address=" + JSON.stringify(Obj_address) + " " +
JSON.stringify(Obj_city) + " " + JSON.stringify(Obj_state) + " " +
JSON.stringify(Obj_zip));

Uncaught Error: Syntax error, unrecognized expression: '.b-brand-box'

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

How can I change the text in just a part of my string with javascript?

I have a javascript string that contains the following:
data-href="/Admin/Edit?pk=0001I&rk=50050055"
How can I change this string so the value of rk is changed to a value held in the string newRowKey? Not sure if it helps but the data format always looks like this with the rk followed by an = and then terminated with the "
datahref="/Admin/Edit?pk=0001I&rk=50050055";
to change it if your building the URL
datahref="/Admin/Edit?pk=0001I&rk="+ newRowKey;
or replace it if you know the existing value
datahref.replace("50050055", newRowKey);
if you do not know the value of rk, but you know its last in the URL, you could use indexOf to find it.
datahref = datahref.substring(0,datahref.indexOf("rk=")+3) + newRowKey;
Maybe you want a regular expression to replace that rk.
newRowKey = 'XXXXXX'
s = 'Edit?pk=0001I&rk=50050055';
s2 = s.replace(/(.*;)(rk=)(.*)(&|)/, '$1$2' + newRowKey)
alert( s + "\n" + s2 );
//2nd test
s = 'Edit?pk=0001I&rk=50050055&';
s2 = s.replace(/(.*;)(rk=)(.*)(&|)/, '$1$2' + newRowKey)
alert( s + "\n" + s2 );
​demo: http://jsfiddle.net/fedmich/g3TjE/
data_href.replace(/rk=.*$/,'rk=' + newRowKey);

Categories

Resources