I have a url like this:
http://mysite.aspx/results.aspx?s=bcs_locations&k="Hospital" OR "Office" OR...
The terms after k= are coming from checkboxes, when checked the checkboxes values are being passed. Now I need to get the current URL and get all the values after k, so if there are two 'Hospital' and Office then grab those values and make the checkboxes with those values checked.. Trying hard to persist the checked checkboxes coz on refresh, all the checked checkboxes loose their state..
Hospitals<input name="LocType" type="checkbox" value="Hospital"/>
Offices<input name="LocType" type="checkbox" value="Office"/>
Emergency Centers<input name="LocType" type="checkbox" value="Emergency"/>
What I have so far is:
I want the regular expression for such URl pattern..can someone help?
var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop("checked", true);
}
This is what we use to grab info from the query string. It's from another S.O. answer that I can't find. But this will give you an object which represents all the options in the query string.
var qs = function(){
var query_string = {};
if(window.location.search){
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q)){
query_string[d(e[1])] = d(e[2]);
}
}());
}
return query_string;
};
You could do it like this:
var MyApp = {
urlArgs:{}
};
MyApp.processUrlArgs = function() {
this.urlArgs = {};
var str = window.location.search ? window.location.search.substring(1) : false;
if( ! str ) return;
var sp = str.split(/&+/);
var rx = /^([^=]+)(=(.+))?/;
var k, v, i, m;
for( i in sp ) {
m = rx.exec( sp[i] );
if( ! m ) continue;
this.urlArgs[decodeURIComponent(m[1])] = decodeURIComponent(m[3]);
}
};
But what I don't understand is why do it like this? If you work in asp why don't you use HttpUtility.ParseQueryString?
try this
function getParamsFromUrl(url){
var paramsStr = url.split('?')[1],
params = paramsStr.split('&'),
paramsObj = {};
for(var i=0;i < params.length; i++){
var param= params[i].split('='),
name = param[0],
value = param[1];
paramsObj[name] = value;
}
return paramsObj;
}
var testUrl = 'http://mysite.aspx/results.aspx?s=bcs_locations&k=Hospital';
getParamsFromUrl(testUrl);//return: Object { s="bcs_locations", k="Hospital"}
Related
I have this code below to search for a string of search string_search_* matched.
I'm wondering if there's any easier way to do this like maybe add multiple search term in indexof? is that possible?
My goal: just add variable string:
string_search4, 5, 6 and so on..
string = "this is a .bigcommerce.com site";
var string_search1 = 'cdn.shopify.com/s';
var string_search2 = '.bigcommerce.com/';
var string_search3 = 'woocommerce/';
// start checkig with SHOPIFY first
var s = string.indexOf(string_search1 );
var found_s = String(s);
// IF FOUND - look for the full url hubspot - like the mp4 url
if (found_s != '-1') {
var result = 'SHOPIFY'
return result;
}
// if NOT FOUND, check with BIGCOMMERCE
else {
var b = html.indexOf(string_search2);
var found_b = String(b);
if (found_b != '-1') {
var result = 'BIGCOMMERCE'
return result;
}
else {
var w = html.indexOf(string_search3);
var found_w = String(w);
if (found_w != '-1') {
var result = 'WOO COMMERCE'
return result;
}
else {
var result = 'CANNOT INDENTIFY CMS'
return result
}
}
}
This may look a little long, but is very expandable.
// Our "key" object and defaults
var sObj = function(id){
this.id = id;
this.found = false;
};
// Our self-contained object with search and result
// functions. This is were and how we can expand quickly
var s = {
'ob': [],
'find': function(haystack) {
if (this.ob) {
for(var x in this.ob) {
this.ob[x].found = (haystack.indexOf(this.ob[x].id) > -1);
}
}
},
'result': function() {
var r = "";
if (this.ob) {
for(var x in this.ob) {
if (this.ob[x].found) {
r += ","+this.ob[x].id;
}
}
}
return (r == "") ? r : r.substr(1);
}
};
// Create the object array with the "id"
// Add as many as you want.
s.ob.push(new sObj('shopify.com'));
s.ob.push(new sObj('bigcommerce.com'));
s.ob.push(new sObj('woocommerce.com'));
// quick debug for testing
//for(var x in s.ob) {
// console.log('x:['+ x +']['+ s.ob[x].id +']['+ s.ob[x].found +']');
//}
// Our string to be tested
var data = "this is a .bigcommerce.com site";
// check if the data matches one of the sObj ids
s.find(data);
// get the results
console.log('result:['+ s.result() +']');
// And for a second test (2 results)
data = "can you shopify.com or woocommerce.com me?";
s.find(data);
console.log('result:['+ s.result() +']');
I need to do as follows:
I've got an array of strings containing last names. Some of them ends with letter 'i'.
manLastNames = ["testowski","bucz","idzikowski","gosz"];
I need to make a function which will iterate over this array of strings and if there is an element ending with 'i', I need to replace this 'i' for 'a', otherwise just leave string as it is.
At the end I want to have another array where all last 'i's are replaced with 'a's.
womanLastNames = ["testowska","bucz","idzikowska","gosz"];
This is what I have now, but Im pretty sure that it start being crap at some point
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = new Array(4);
for (var i=0; i<manLastNames.length; i++) {
var lastName = manLastNames[i];
if (lastName.substr(lastName.length - 1, 1) == 'i') {
lastName = lastName.substr(0, lastName.length - 1) + 'a';
}
}
for (var i=0; i<womanLastNames.length; i++) {
womanLastNames[i] = lastName[i];
}
console.log(womanLastNames);
}
rep();
Try the code:
var manNames = ["testowski","bucz","idzkowski","gosz"];
var womanNames = manNames.map(function(name) {
return name.endsWith("i") ? name.slice(0, -1) + "a" : name;
});
console.log(womanNames)
If your interpreter supports ES6, the following is equivalent:
names.map((name)=>name.endsWith("i") ? name.slice(0, -1) + "a" : name)
Here is solution
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames =[];
for (var i=0; i<manLastNames.length; i++) {
var lastName = manLastNames[i];
if (lastName.charAt(lastName.length - 1) == 'i') {
lastName = lastName.substr(0, lastName.length - 1) + 'a';
}
womanLastNames.push(lastName);
}
console.log(womanLastNames);
}
rep();
Another solution is to use .map method like this, using a callback function:
var manLastNames = ["testowski","bucz","idzikowski","gosz"];
function mapNames(item){
return item[item.length-1]=='i' ? item.substr(0, item.length-1) + "a" : item;
}
console.log(manLastNames.map(mapNames));
Depending on how efficient you need to be, you can use regular expressions to do both tasks:
var new_name = name.replace(/i$/, 'a');
will replace the last "i" in a string with "a" if it exists
var new_name = name.replace(/i/g, 'a');
will replace all "i"s in a string with "a".
var names = ["testowski", "bucz", "idzkowski", "gosz"];
console.log("original", names);
var last_i_replaced = names.map(function(name) {
return name.replace(/i$/, 'a');
});
console.log("last 'i' replaced", last_i_replaced);
var all_i_replaced = names.map(function(name) {
return name.replace(/i/g, 'a');
});
console.log("all 'i's replaced", all_i_replaced);
This should work:
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = manLastNames;
for(var i=0; i<manLastNames.length;i++){
if(manLastNames[i].charAt(manLastNames[i].length-1)=='i'){
womanLastNames[i]=manLastNames[i].substr(0,womanLastNames[i].length-1)+'a';
}
}
console.log(womanLastNames);
}
rep();
Here is another solution
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = []
manLastNames.forEach(x => {
if (x.charAt(x.length-1) === "i") womanLastNames.push(x.slice(0,-1).concat("a"));
else womanLastNames.push(x);
});
console.log(womanLastNames);
There are a couple of similar questions but none covers the case when a string looks like some-name[][some-key]. I have tried JSON.parse('some-name[][some-key]'); but it doesn't parse it.
Is there a way to convert such string to a JavaScript object that will look like { 'some-name': { 0: { 'some-key': '' } } }?
This is a name of a form field. It's normally parsed by PHP but I'd like to parse it with JavaScript the same way. I basically have <input name="some-name[][some-key]"> and I'd like to convert that to var something = { 'some-name': { 0: { 'some-key': VALUE-OF-THIS-FIELD } } }.
Try this:
JSON.parse('{ "some-name": [ { "some-key": "" } ] }');
I don't know exactly how you're doing this, but assuming they are all that format (name[][key]) and you need to do them one by one - this works for me:
var fieldObj = {};
function parseFieldName(nameStr)
{
var parts = nameStr.match(/[^[\]]+/g);
var name = parts[0];
var key = typeof parts[parts.length-1] != 'undefined' ? parts[parts.length-1] : false;
if(key===false) return false;
else
{
if(!fieldObj.hasOwnProperty(name)) fieldObj[name] = [];
var o = {};
o[key] = 'val';
fieldObj[name].push(o);
}
}
parseFieldName('some-name[][some-key]');
parseFieldName('some-name[][some-key2]');
parseFieldName('some-name2[][some-key]');
console.log(fieldObj); //Firebug shows: Object { some-name=[2], some-name2=[1]} -- stringified: {"some-name":[{"some-key":"val"},{"some-key2":"val"}],"some-name2":[{"some-key":"val"}]}
o[key] = 'val'; could of course be changed to o[key] = $("[name="+nameStr+"]").val() or however you want to deal with it.
Try this:
var input = …,
something = {};
var names = input.name.match(/^[^[\]]*|[^[\]]*(?=\])/g);
for (var o=something, i=0; i<names.length-1; i++) {
if (names[i])
o = o[names[i]] || (o[names[i]] = names[i+1] ? {} : []);
else
o.push(o = names[i+1] ? {} : []);
}
if (names[i])
o[names[i]] = input.value;
else
o.push(input.value);
Edit: according to your updated example, you can make something like this (view below). This will work - but only with the current example.
var convertor = function(element) {
var elementName = element.getAttribute('name');
var inpIndex = elementName.substring(0, elementName.indexOf('[')),
keyIndex = elementName.substring(elementName.lastIndexOf('[') + 1, elementName.lastIndexOf(']'));
var strToObj = "var x = {'" + inpIndex + "': [{'" + keyIndex + "': '" + element.value + "'}]}";
eval(strToObj);
return x;
};
var myObject = convertor(document.getElementById('yourInputID'));
Example here: http://paulrad.com/stackoverflow/string-to-array-object.html
(result is visible in the console.log)
old response
Use eval.. but your string must have a valid javascript syntax
So:
var str = "arr[][123] = 'toto'";
eval(str);
console.log(arr);
Will return a syntax error
Valid syntax will be:
var str = "var arr = []; arr[123] = 'toto'";
var x = eval(str);
console.log(arr);
I need to get the URL search paramentes in an object, for eg; http://example.com/?a=x&b=y&d#pqr should yield {a:x, b:y, d:1}
Below is the method i used to get this, How can i improve this? any suggessions...
var urlParamKeyVals = new Array();
var pieces = new Array();
var UrlParams = {};
if(window.location.search.length){
var urlSearchString = window.location.search;
if(urlSearchString.charAt(0) == '?'){
urlSearchString = urlSearchString.substr(1);
urlParamKeyVals = urlSearchString.split("&");
}
}
for (var i = 0; i<urlParamKeyVals .length; i++) {
pieces = urlParamKeyVals [i].split("=");
if(pieces.length==1){
UrlParams[pieces[0]]=1;
} else {
UrlParams[pieces[0]]=pieces[1];
}
}
UrlParams;
I've made some time ago a small function for the same purpose:
Edit: To handle empty keys as 1:
function getQueryStringValues (str) {
str = str || window.location.search;
var result = {};
str.replace(/([^?=&]+)(?:[&#]|=([^&#]*))/g, function (match, key, value) {
result[key] = value || 1;
});
return result;
}
getQueryStringValues("http://example.com/?a=x&b=c&d#pqr");
// returns { a="x", b="c", d=1 }
function getParams(q){
var p, reg = /[?&]([^=#&]+)(?:=([^&#]*))?/g, params = {};
while(p = reg.exec(q)){
params[decodeURIComponent(p[1])] = p[2] ? decodeURIComponent(p[2]) : 1;
}
return params;
}
getParams(location.search);
-- edit
I extended the regular expression to match also the ¶m (no value) and ¶m= (empty value) cases. In both cases the value 1 is returned. It should also stop extracting on hash (#) character. Decoding values also supported.
jQuery bbq has a nice deparam method if you are trying to look at some very stable code:
http://github.com/cowboy/jquery-bbq/
http://benalman.com/code/projects/jquery-bbq/examples/deparam/
function getObjectFromSearch() {
var search = location.search;
var searchTerms = [];
var obj = {};
if (search !== '') {
search = search.replace(/^\?/,'');
searchTerms = search.split("&");
}
for (var i=0, imax=searchTerms.length; i<imax; i++) {
var ary = searchTerms[i].split("=");
obj[ary[0]] = ary[1];
}
return obj;
}
I have the following code that worked fine till now as I decided to add more variables to the form. How can I make this function smart and itterate and pass all the variables in the form?
function getquerystring(strFormName) {
var form = document.forms[strFormName];
var word = form.clock_code.value;
qstr = 'clock_code=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
complete JS code # pastie
It looks like you're serializing a form to a querystring? If that's the case, then this is one place where a JavaScript library is really nice.
Each of these will serialize the first form on the page to a querystring.
// ExtJS
var str = Ext.lib.Ajax.serializeForm(Ext.select('form').elements[0]);
// jQuery
var str = $("form").serialize();
// MooTools
var str = $$('form').toQueryString();
// PrototypeJS
var str = $$('form')[0].serialize();
You can see some other methods and how they compare at http://jquery.malsup.com/form/comp/
Try this
function formToQueryString(form) {
var elements = form.elements;
var cgi = [];
for (var i = 0, n = elements.length; i < n; ++i) {
var el = elements[i];
if (!el.name) { continue; }
if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')
&& !el.checked) {
continue;
}
cgi.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
}
return cgi.length ? '?' + cgi.join('&') : '';
}
The issue with your code is that you're only grabbing the clock_code element value, and ignoring the rest. Here's a replacement I wrote up:
function getquerystring(strFormName) {
var qstr = '', word = '';
var key = 0;
var form = document.forms[strFormName];
var fields = ['clock_code', 'message', 'type'];
for (var i = 0; i<fields.length; i++) {
key = fields[i];
word = form[key].value;
if (qstr && qstr.length > 0) {
qstr += '&';
}
qstr += encodeURIComponent(key) + '=' + encodeURIComponent(word);
}
return qstr;
}
Benjamin's approach is a bit more flexible; mine only queries those fields specifically named in the fields array
Assuming they are all simple fields, the following should work just fine (didn't test it, though - sorry if it doesn't "compile"):
function getquerystring(strFormName) {
var qstr = '';
var form = document.forms[strFormName];
var elements = form.elements;
var first = true;
for (elem in elements) {
var word = elem.value;
var name = elem.name;
if (first) {
first = false;
} else {
qstr = qstr + '&';
}
qstr = qstr + name + '=' + escape(word);
}
return qstr;
}
Adding info on supporting multiple Element types:
The question only mentioned text fields so I assumed the easier answer would suffice. Wrong!
Glad you're able to use JQuery (which rocks), but for completeness I'll just flesh this out with a bit of info on how to build your own "dynamic form handler".
First, you have to add checking on the class of elem, like so:
function isCheckbox(o){ return (o && o.constructor == Checkbox) }
and you have to then do something a little different depending on the type of object you are looking at.
For example:
for (var elem in elements) {
var value = '';
var name = elem.name;
if (isCheckbox(elem)) {
value = elem.checked ? 'true' : 'false';
} else if (isSingleSelect(elem)) {
var index = elem.selectedIndex;
if(selected_index > 0) {
value = elem.options[selected_index].value;
}
}
}
There may be situations where you have to turn values into something that is meaningful to your app, like in a multiple-select combo box. You could send one name=value pair for each value or roll them into a comma-seperated list or the like - it all depends on your app. But with this approach one can certainly build the "dynamic form handler" that fits their specific needs.
Check out this article for helpful stuff about how to process each form field type: http://www.javascript-coder.com/javascript-form/javascript-get-form.htm