Can I do string formatting in Javascript? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript equivalent to printf/string.format
I am creating code like this:
var ds = "ds=" + encodeURIComponent($('#DataSource').val());
var ex = "ex=" + encodeURIComponent($('#EID').val());
var to = "to=" + encodeURIComponent($('#TID').val());
var st = "st=" + encodeURIComponent($('#SID').val());
window.location.href = '/person?' + ds + "&" + ex + "&" + to + "&" + st;
Is there some way in Javascript that I could use formatting to make the code look a bit cleaner? Also do I need to encode each element or can I just encode the variable abc?

There's not a lot you can do, really. You could alias the encodeURIComponent method and use an array with join() if you're looking for something a little neater:
var e = encodeURIComponent,
arr = [
"ds=" + e($('#DataSource').val()),
"ex=" + e($('#EID').val()),
"to=" + e($('#TID').val()),
"st=" + e($('#SID').val())
];
window.location.href = '/person?' + arr.join("&");

Use <form> and put your input tags in them and you can call $('formContainer').serialize();
Its better to use name-value pairs(query strings), while sending data to URI. provide names as id to all of the input tags that you wish to capture. You will get something like:
/person/DataSource=ds&EID=ex&TID=to&SID=st
-HTH

Why don't you just write:
window.location.href = encodeURIComponent('/person?' +
$('#DataSource').val() + "&"
+ $('#EID').val() + "&" + $('#TID').val() + "&"
+ $('#SID').val());

Take a look at sprintf()
Also this can help: JavaScript equivalent to printf/string.format

var str = "/person?ds=%x&ex=%x&to=%x&st=%x";
var tokens = [
$("#DataSource").val(),
$("#EID").val(),
$("#TID").val(),
$("#SID").val()
];
tokens.forEach(function (token) {
str = str.replace("%x", encodeURIComponent(token));
});
location.href = str;
This will absolutely fall over if you have %x in your token string.
If you want a more generic solution try underscore.string

Related

JS/JQUERY: How to match and replace occurances inside specified strings?

I swear i tried figuring this out myself all day, but my regex-foo is just not that good.
I'm trying to create a small parser function to convert strings with urls to html coded and tags
I know how complex a regex can be trying to figure out which urls to covert to what from a big string, so what I did is simply prefix the string to covert with a flag to tell the parser how to format it, and post fix it with the ";" char to tell the parser where that particular URL ends. This way the parser has lesser guest work to do resulting in easier to regex-match and faster for execution. I really dont need a generalize match and replace all.
So my formatting is as follows, where "X" is the url string:
For URLs it will be url=X;
For IMAGES it will be img=X;
so anything in between my prefix and post fix must be converted accordingly..
So for example, for images in my document, the string could be:
click this image img=http://example.com/image1.jpg;
and i need that converted to
click this image <a href="http://example.com/image1.jpg" target="_blank">
<img class="img img-responsive" src="http://example.com/image1.jpg"/></a>
I am able to do this easily in PHP buy preg_match() function
preg_match('/\img=(.+?)\;/i', $item_des, $matches)
here's the code block:
I decided to push this routine to the browser instead of the backend (PHP) so i need similar or better JS solution.
Hoping anyone can help here, thanks!
try code below:
var str = "click this image img=http://example.com/image1.jpg;image2 img=http://example.com/image2.jpg;"
var phrases = str.split(';');
var totalRes = '';
phrases.forEach(function(str){
totalRes += processPhrase(str);
});
console.log(totalRes);
function processPhrase(str) {
var img = str.split('img=')
var res = '';
if (img.length > 1) { //img=X
var url = img[1].replace(';', '');
res = img[0] + "<a href='" + url + "' target='_blank'><img src='" + url + "'/></a>";
} else {
var url = str.split('url=');
//Do for url=X here
}
console.info(res);
return res;
}
You can use this regexp /(img|url)=(.+?);/g:
(img|url) : the type, should be grouped so we will know what to do with the value
= : literal "="
(.+?) : a number of characters (use the non-greedy ? so it will match as fewer as possible)
; : literal ";"
Read more about non-greedy regexps here.
Example:
var str = "click this image img=http://i.imgur.com/3wY30O4.jpg?a=123&b=456; and check this URL url=http://google.com/;. Bye!";
// executer is an object that has functions that apply the changes for each type (you can modify the functions for your need)
var executer = {
"url": function(e) {
return '<a target="_blank" href="' + e + '">' + e + '</a>';
},
"img": function(e) {
return '<a target="_blank" href="' + e + '"><img src="' + e + '"/></a>';
}
}
var res = str.replace(/(img|url)=(.+?);/g, function(m, type, value) {
return executer[type](value); // executer[type] will be either executer.url or executer.img, then we pass the value to that function and return its returned value
});
console.log(res);

In JavaScript, what is the simplest way to insert text into a string?

I have an issue where I need to take a string (which is a query string) in JavaScript and transform it into another query string (to avoid clashes).
The original string I have comes in as:
fieldA=10&fieldB=10&fieldC=10&fieldD=10&arrayfieldA=100&arrayfieldA=200
And I want to take a prefix (in my case it will be something like "slides[0]." and put it in front of all of the items, so I end up with:
slides[0].fieldA=10&slides[0].fieldB=10&slides[0].fieldC=10&slides[0].fieldD=10&slides[0].arrayfieldA=100&slides[0].arrayfieldA=200
In JavaScript, what is the simplest way to transform the first string into the second?
I could use
Simple find / "replace()" (.replace("&", "&slides[0]")
Convert to array and then spit back to a concatenated string
others?
Currently I am doing this:
function EnrichString(startString, prefix) {
return prefix + startString.replace("&", "&" + prefix);
}
But I wanted to confirm if there are any gotchas with this approach?
Use:
var queryStringParts = queryString.split('&');
var pairs = queryStringParts.map(function(str) { return str.split('=') })
var rewrittenParts = pairs.map(function(pair){
return 'slides[0].' + pair[0] + '=' + pair[1]
});
var newQuerystring = rewrittenParts.join('&');
As was pointed out in the comments, in this specific case we could skip the split into pairs step and just do
var queryStringParts = queryString.split('&');
var rewrittenParts = queryStringParts.map(function(part) {
return 'slides[0].' + part
});
var newQuerystring = rewrittenParts.join('&');

How to get current URL with JavaScript? [duplicate]

This question already has answers here:
Get current URL with jQuery?
(33 answers)
Closed 8 years ago.
I have this portion of the code. I want to know how can I read the url as the current page instead a fix url
Here is the portion of the coding:
var str='';
if(model_id != 0 ) str = model_id+"+";
if(year_id != 0 ) str +=year_id+"+";
url='http://store.ijdmtoy.com/SearchResults.asp?Search='+str;
top.location.href=url;
You see currently it has a fix reading the url http://store.ijdmtoy.com/SearchResults.asp
For example, I am currently on http://store.ijdmtoy.com/abs.htm
How can I change the code so it will automatically read as http://store.ijdmtoy.com/abs.htm?searching=Y&Search
If you are currently on http://store.ijdmtoy.com/abs.htm then document.URL will be http://store.ijdmtoy.com/abs.htm.
You can try:
url = location.protocol + '//' + location.host + location.pathname + '?Search=' + str;
You can use
document.URL or
window.location.href.toString()
I hope you mean this
http://jsfiddle.net/AmarnathRShenoy/q3yCA/
Use this code
document.URL
Ex:
alert(document.URL);
You can get path split like
var split=document.URL.split("/");
rather than using top.location.href=url;
you can use window.location = url;
var pathname = document.URL + 'Search=' + str;
Get it from window.location, as it is an object "cast it" to an string:
var global = (function(){ return this; })() ;
var str='';
if(model_id != 0 ) str = model_id+"+";
if(year_id != 0 ) str +=year_id+"+";
url= '' + global.location + '?Search='+str;
top.location.href=url;
If you just want to replace the query string use this:
window.location.search = "?searching="+str+"&Search";
you can use window.location.pathname

how to convert to array in js?

I have this string which I want to convert to an array:
var test = "{href:'one'},{href:'two'}";
So how can I convert this to an array?:
var new = [{href:'one'},{href:'two'}];
It depends where you got it from..
If possible you should correct it a bit to make it valid JSON syntax (at least in terms of the quotes)
var test = '{"href":"one"},{"href":"two"}';
var arr = JSON.parse('[' + test + ']');
Notice the " around both keys and values.
(making directly var test = '[{"href":"one"},{"href":"two"}]'; is even better)
If you could modify the original string to be valid JSON then you could do this:
JSON.parse(test)
Valid JSON:
var test = '[{"href":"one"},{"href":"two"}]';
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj is your JSON object.
If changing the string to be valid JSON is not an option, and you fully trust this string, and its origin then I would use eval:
var test = "{href:'one'},{href:'two'}";
var arr = eval("[" + test + "]");
On that last note, please be aware that, if this string is coming from the user, it would be possible for them to pass in malicious code that eval will happily execute.
As an extremely trivial example, consider this
var test = "(function(){ window.jQuery = undefined; })()";
var arr = eval("[" + test + "]");
Bam, jQuery is wiped out.
Demonstrated here

Javascript: replace inside a replace

My input is many lines of text that looks like this:
a.b.c.d.e (f:g)
I need to turn this into
a.b.c.d.e (a/b/c/d/e/f?g)
Note that the dotted part (a.b.c.d.e) can have varying numbers of elements, so sometimes it'll be q.r.s.t, sometimes u.v.w.x.y.z and so on. I have a replace() that will give me (a.b.c.d.e.f?g), but what I need is then to turn all those .s into /s in the result.
Is there a way to do a replace inside a replace? Or should I just call replace() on the string twice?
Sorry if this question is poorly worded, I'm not awfully well versed at regular expressions in javascript.
A very crazy way of doing it:
var str = "a.b.c.d.e (f:g)";
var re = /([^\s]+)\s\(([^:]+):([^\)]+)\)/;
var newStr = str.replace(re, function(a,b,c,d){ return b + " (" + b.replace(/\./g,"/") + "/" + c + "?" + d + ")"; });
jsfiddle
You need to chain the calls to replace() one after the other.
var result = source.replace("foo", "bar").replace("oof", "rab");
A saner way :) http://jsfiddle.net/smfPU/
input = "a.b.c.d.e.w.x.y.z (f:g:h)";
output = input.replace(/:/g, "?");
outputparts = output.split("(");
left = outputparts[0];
middle = left.replace(/\./g, "/").trim();
right = outputparts[1];
output = left + "(" + middle + "/" + right;
document.write(output);

Categories