javascript how to add a variable to a string - javascript

I'm using javascript and jquery, I have a string like
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{ids}?order=desc&sort=activity&site=stackoverflow';
I need replace the {ids} with a variable.
In C# is possible to use a method called
String.Format(https://api.stackexchange.com/2.0/answers/{0}?order=desc&sort=activity&site=stackoverflow, myVariable);
I would like to know if exist something similar in Javascript so I can avoid simple string concatenation.
Thanks for your help!

Use the String .replace() method:
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{ids}?order=desc&sort=activity&site=stackoverflow';
apiUrlAnswer = apiUrlAnswer.replace("{ids}", yourVariable);
// OR, if there might be more than one instance of '{ids}' use a regex:
apiUrlAnswer = apiUrlAnswer.replace(/\{ids\}/g, yourVariable);

Well here's a String.format (like c#); I've extended javascripts String object to include a format method like this:
String.format = function(stringToFormat, argsForFormat) {
for (var i = 0; i < argsForFormat.length; i++) {
var regex = new RegExp('\{(' + i + ')}', 'g');
stringToFormat = stringToFormat.replace(regex, argsForFormat[i]);
}
return stringToFormat;
};
You can call it like this
var args = [1, 'activity', 'stackoverflow', 'desc']
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/{0}?order={3}&sort={1}&site={2}';
var apiUrlAnswer = String.format(apiUrlAnswer, args);
Or an inline version would look like this
var apiUrlAnswer = String.format('https://api.stackexchange.com/2.0/answers/{0}?order={3}&sort={1}&site={2}', [1, 'activity', 'stackoverflow', 'desc']);
and another example
String.format("http://{0}.{1}.com", ['www', 'stackoverflow']);

If you are doing this frequently, a more robust alternative to using a regex is to use a client side templating engine like mustache.js. I have used this successfully and it's quick and lightweight.
var view = {
ids: "Andrew"
};
var output = Mustache.render("https://api.stackexchange.com/2.0/answers/{{ids}}?order=desc&sort=activity&site=stackoverflow", view);
This has the advantage of separating your data and presentation nicely.

How about just using replace:
apiUrlAnswer = apiUrlAnswer.replace('{ids}', 'test');

Try
var id = 'your_id';
var apiUrlAnswer = 'https://api.stackexchange.com/2.0/answers/'+id+'?order=desc&sort=activity&site=stackoverflow';

Related

Invoke method (that takes string param) on string via chaining

Can I do something like this?
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = mystring.apply(decodeURIComponent);
I know I can do this
var mydecodedstring = decodeURIComponent(mystring);
But I'd like to chain this if possible for syntactic purposes. Just curious if it's possible. My goal is:
mystring.?????
Your should see this to see how apply works. You could do something like:
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = decodeURIComponent.apply(null, mystring);
Clearly, apply will not provide what you are looking for.
You could define your own function on the String prototype for decoding or define it only on your object.
maybe you want to add a new method to String object?
String.prototype.apply= function(entry){
return decodeURIComponent(entry);
}
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = mystring.apply(decodeURIComponent);

InDesign Target XML Structure element by partial name

In my Structure pane there are some elements that their partial name is identical, eg. image01, image03, image03 etc.
I want to know if there is a way to access them via scripting using the itemByName() method, but by providing a partial name, like in CSS i can use
h1[rel*="external"]
Is there a similar way to do this in:
var items2 = items.xmlElements.itemByName("image");
You could try something like the code below. You can test against the markupTag.name properties with a regular expression. The regex is equivalent to something like /^image/ in your example (find image at the beginning of a string).
function itemsWithPartialName(item, partialName) {
var elems = item.xmlElements;
var result = [];
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
var elemName = elem.markupTag.name;
var regex = new RegExp("^" + partialName);
if (regex.test(elemName)) {
result.push(elem);
}
}
return result;
}
itemsWithPartialName(/* some xml item */, 'image');
You can use an XPath:
var rootXE = app.activeDocument.xmlElements.item(0);
var tagXEs = rootXE.evaluateXPathExpression("//*[starts-with(local-name(),'image')]");

Search URL parameters with Angular JS

Say I have a URL like this:
www.mysite.com?account=23&token=asdu756sdg65sdf
Now, I need to access those URL parameters individually using Angular JS.
I've tried using location.search inside my controller:
console.log(location.search);
Which nicely returns the full query string:
?account=23&token=asdu756sdg65sdf
But it seems to return a string, not an object. Is there an easy way to access the individual ids and values in the string?
I've also tried:
console.log($location.search());
Which seems to return an empty object.
Try with
var account = ($location.search()).account;
but the url should be like /#!/?account=1
have your tried using it as a function instead?
$location.search();
pure js way:
var getParamFromURL = function(_url) {
var url = _url;
var _paraString = url.indexOf("&") > -1 ? url.substring(url.indexOf("?") + 1, url.length).split("&") : url.substring(url.indexOf("?") + 1, url.length).split('');
var _paraObj = {};
for (i = 0; p = _paraString[i]; i++) {
_paraObj[p.substring(0, p.indexOf("=")).toLowerCase()] = p.substring(p.indexOf("=") + 1, p.length);
}
return _paraObj;
}
via angular js:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
Great. #Cooper is right.

JS How to include a variable in a path?

The following variable contains a string that is a path to an image.
iconBlue.image = 'http://www.site.com/icon1.jpg';
How can include a variable in this path? Let me explain more detailed. Lets say there are many icons in a folder icon1.jpg icon2.jpg etc. I have a variable named iconspec that depending on its value (1 or 2 or 3 etc) points to the icon I must use.
How can i include variable iconspec in the path?
iconBlue.image='http://www.site.com/icon"iconspec".jpg
Something like this i guess but with correct syntax.
You just need to put it like a simple string with variable.
In your case, you should do this:
iconBlue.image = 'http://www.site.com/icon'+iconspec+'.jpg';
The + operator is like the . in PHP, it merge string.
iconBlue.image='http://www.site.com/icon'+iconspec+'.jpg';
To take a little different route, you could encapsulate the concatenation in a function and make it a bit more reusable:
var icon = function(){
this.path = '';
this.imageName = '';
this.imagePath = function() { return this.path + '/' + this.imageName };
};
var iconBlue = new icon(),
iconRed = new icon();
iconBlue.path = "c:\\stuff";
iconBlue.imageName = "icon1.jpg";
iconRed.path="c:\\morestuff";
iconRed.imageName = "icon2.jpg";
alert(iconBlue.imagePath());
alert(iconRed.imagePath());
The simplest solution is to use the + to concatenate the variable to the string:
var name = 'sachleen';
var result = 'my name is ' + name;
Output: my name is sachleen
There are a couple of more powerful options available as well.
JavaScript sprintf() is a sprintf implementation for JS.
string.format in JS

How to substring the string using jQuery

I am using jQuery
I have got below in my string
str = "Michael,Singh,34534DFSD3453DS"
Now I want my result in three variables.
str1 = "Michael"
str2 = "Singh"
str3 = "34534DFSD3453DS"
Please suggest!
Thanks
var strs = str.split(',') is your best bit. This will create an array for you so
strs[0] = "Michael"
strs[1] = "Singh"
strs[2] = "34534DFSD3453DS"
However, it is possible to get exactly what you want by adding new items to the window object. For this I use the $.each method of jQuery. It's not necessary (you can just use a for) but I just think it's pretty :). I don't recommend it, but it does show how you can create new variables 'on the fly'.
var str = "Michael,Singh,34534DFSD3453DS";
$.each(str.split(','), function(i,item){
window['str' + (i+1)] = item;
});
console.log(str1); //Michael
console.log(str2); //Singh
console.log(str3); //34534DFSD3453DS
Example: http://jsfiddle.net/jonathon/bsnak/
No jQuery needed, just javascript:
str.split(',')
Or, to get your 3 variables:
var arr = str.split(','),
str1 = arr[0],
str2 = arr[1],
str3 = arr[2];
You don't need jQuery. Javascript does that built-in via the split function.
var strarr = str.split(',');
var str1 = strarr[0];
var str2 = strarr[1];
var str3 = strarr[2];
Just use split() and store each word inside an array
var str = "Michael,Singh,34534DFSD3453DS"
var myArray = str.split(",");
// you can then manually output them using their index
alert(myarray[0]);
alert(myarray[1]);
alert(myarray[2]);
//or you can loop through them
for(var i=0; i<myArray.length; i++) {
alert(myArray[i]);
}
It's not only that JQuery is not needed but that JQuery is not meant to do such tasks. JQuery is for HTML manipulation, animation, event handling and Ajax.

Categories

Resources