If I re-rite the URL using :
var id = 150
window.location.hash = "id="+id;
how to get the value of id using jQuery ?
No jQuery needed..
var id = /^#?id=(.+)/.exec(location.hash);
id = id ? id[1] : '';
// OR
var id = location.hash.substr(4); // (when hash can only be #id=..)
// This also selects 123 in #no=123 (!)
+1 for Rob W's answer not to use jQuery for this. But there're two things, i'd like to point out.
1.) Executing a regular expression, plus using a tertiary operator is "overload", too. ;-)
2.) You should consider that some browers return the hash symbol, and some don't!
To avoid to truncate the actual value part, I'd say it's safer to use replace(), instead of substr():
var id = location.hash.replace('id=', '').replace('#', '');
UPDATE:
I think split() is an even better solution:
var id = location.hash.split('id=')[1];
Just one (native) function call, which also "checks" if the request URL actually contains a hash that contains the string "id=idString".
If it does, the value of var id is "idString". If not, value of var id is undefined.
Related
How can I remove a single word from an ID using Jquery?
For example, I have a div with ID page_getstarted and I want to get that ID in jquery and use it for something else but I don't want to use that whole ID I just want to use get_started.
Is there a way to get an id and trim it?
Since you mentioned that you already know how to get the id attribute, I'll suggest you to create a function to check a specified string param (in your case you need to pass the id attribute), check if it contains the word you want to remove, if it does you'll remove and return the modified string which you can store in a variable to reuse. For instance like so:
const removeStrFromId = (strId, searchQuery) => (strId.includes(searchQuery) ? strId.replace(searchQuery, "") : "");
const newModifiedStr = removeStrFromId("page_getstarted", "page_");
console.log(newModifiedStr); // outputs the string "getstarted"
You can reuse this function to manipulated other strings in the future if needed...
you can fetch id as
var container = $('#page_getstarted');
idText = container.attr('id'));
then use javascript to manipulate your string use split/replace method.
var idParts= idText.split("_");
var myId = idParts[1];
Have this
var cData={};
var arr=[];
datacolumns.split(",").forEach((element)=>{
arr.push({data:element.trim()})
cData[element] = `$(#${element.trim(0)}).val()`;
});
but when I call the cData in the ajax Data:cData, it is sending the form as
authorid "$(#authorid).val()"
firstname "$(#firstname).val()"
lastname "$(#lastname).val()"
sorted "$(#sorted).val()"
what is going on here, I have zero clue
I think you're using the backticks incorrectly. If element is a string, you should not need to use them.
var cData={};
var arr=[];
datacolumns.split(",").forEach((element)=>{
var el = element.trim();
arr.push({ data: el });
cData[el] = $("#" + el).val();
});
So as you go through the loop, you should get a new selector each time:
$("#authorid").val();
$("#firstname").val();
$("#lastname").val();
$("#sorted").val();
As long as these elements exist with the proper ID and have value attributes, this should work to populate your Object.
Well, you have a little problem with your code. You need to change this:
cData[element] = `$(#${element.trim(0)}).val()`;
to this:
cData[element] = $(`#${element.trim(0)}`).val();
Note the placement of the backticks (`). You have wrapped the whole right-hand operand into the backticks which made it a string while what you really wanted to achieve was to wrap only the selector part.
I was wondering if it is necessary to check for the condition in this particular example.
The condition I'm talking about is if ( Id.indexOf("_") ).
It just checks to see if Id has an underscore and if so then set the variable to strip the underscore and replace with hyphen.
I know I can just use Id = Id.split("_").join("-"); without the if statement checking to see if the condition is true, but just wondering if in this case is it good practice to check for the condition first or not?
Which way would you do it? And explain why please.
Id = "My_ID";
var brand = "The Brand";
var b = brand.trim().toLowerCase();
var page = b.split(/\W+/g).join("-");
if ( Id.indexOf("_") ) {
Id = Id.split("_").join("-");
}
If there is no underscore your split() won't do anything, so no - there's no need for the if here. Go with something like that and you're fine:
Id = Id.split("_").join("-");
or
Id = Id.replace(/_/g, '-');
to avoid creating an array first.
This could answer your question:
console.log("mytext".split("_").join("-")); // mytext
console.log("my_text".split("_").join("-")); // my-text
furthermore condition in your code if (Id.indexOf("_")) does not work as you intended. You need to use if (Id.indexOf("_") > -1) or (~Id.indexOf("_"))
What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();
i have an URL like the followin,
http://test.com/testing/test/12345
12345 is the id. I want to take this using query string. How to take this value in javascript?
try like this
http://test.com/testing/test/12345
var aarr = window.location.href.split('/');
//get last value
var id = aarr[aarr.length -1];
or just
var id = window.location.href.split('/').pop()
Use this :
document.location.href.split('/').pop()
Running it on this page yields : 22139563#22139563
Use this code:
var id = location.split('/').pop();
That's part of the path, not the query string... but you can access the page's URL using window.location.
The path is available at window.location.pathname which can be split up using forward slashes: window.location.pathname.split('/')
And then you can get the last item of the array: window.location.pathname.split('/').pop()
I would use substring, I think it's lighter than creating an array:
var id = window.location.href;
id = id.substring(id.lastIndexOf('/')+1);