Split last word value in JavaScript string [duplicate] - javascript

This question already has answers here:
How to retrieve GET parameters from JavaScript [duplicate]
(17 answers)
Closed 7 years ago.
I have a URL string in JavaScript below ex-
URL-"/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567"
Now, I need to do below 2 things
Check whether the country exists in above url or not and there will be only one countryId in above url
Get the countryId value means 875567.
Thanks Guys for such good response quickly .I got the solution most of the answers are correct.
One More Question Guys I have hyperlink so i am generating some activities when onmousedown event .but the issue is it fires even when i do right click only..but i want the event which fires only on clicking the hyperlink double click or right click and then click

Fetch URL using
window.location.href
And
Split with '?' first, '&' next and '=' so that you can get countryId
OR
directly split with '=' and get last value from array that we get after split

You need to use a combination of indexOf() and substring()
var ind = url.indexOf("countryId");
if (ind != -1){
// value is index of countryid plus length (10)
var countryId = url.substring(ind+10);
}else{
//no countryid
}

How about something like this:
var TheString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
var TheCountry = parseInt(TheString.split('=').pop(), 10);
And then you just need to test if TheCountry is something with if (TheCountry) { ...}
This of course assumes that the URL query string will always have the country ID at the end.

var url ='/MyProject/Information/EmpDetails.aspx?userId=79874& countryId=875567';
alert((url.match(/countryId/g) || []).length);
alert(url.substring(url.lastIndexOf('=')+1));
you can get the count of the occurrence of any string in first alert and get the countryid value by substring.

This will convert your url query into an object
var data = url.split('?')[url.split('?').length - 1].split('&').reduce(function(prev, curr){
var fieldName = curr.split('=')[0];
var value = curr.split('=').length > 1 ? curr.split('=')[1] : '';
prev[fieldName] = value;
return prev
}, {});
then you can just check the value of data.country to get the value

You may also split the string and see if the countryId exists, as below.
var myString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
myString = myString.split("countryId="); //["/MyProject/Information/EmpDetails.aspx?userId=79874&", "875567"]
if (myString.length === 2) {
alert (myString.pop());
}

Related

Replace specific value in URL String in JavaScript

I have a String having URL like:
var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/3/?options=cart";
I am getting quantity on button click from input as well like:
var qty = jQuery(this).siblings('.quantity-field').val(); // 4
How can I change this qty in URL String "/qty/3/" to "/qty/4/" on every time I get new value from input on button click?
I can't simply find and replace because i don't know /qty/3 exact number its dynamic it could be 2,3,4,5 etc
here is function for having this functionality
function changeValue(str,value){
return str.replace(/\/qty\/[0-9]+\//,`\/qty\/${value}\/`)
}
console.log(url,4);
You can use replace method.
capture everything up to /qty in group 1 (g1), all the following digits in group 2 (g2), and remaining in group 3 (g3), in callback change value of group 2 as required.
var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/3/?options=cart";
let desired = url.replace(/^(.*\/qty\/)(\d+)(.*)$/g, function(match,g1,g2,g3){
return g1+ (Number(g2)+1) + g3
})
console.log(desired)

Parse URL which contain string of two URL

I've node app and Im getting in some header the following URL and I need to parse it and change the content of 3000 to 4000 ,How can I do that since Im getting "two" URLs in the req.headers.location
"http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node"
The issue is that I cannot use just replace since the value can changed (dynmaic value ,now its 3000 later can be any value...)
If the part of the URL you always need to change is going to be a parameter of redirect_uri then you just need to find the index of the second %3A that comes after it.
Javascript indexOf has a second parameter which is the 'start position', so you can first do an indexOf the 'redirect_uri=' string, and then pass that position in to your next call to indexOf to look for the first '%3A' and then pass that result into your next call for the %3A that comes just before your '3000'. Once you have the positions of the tokens you are looking for you should be able to build a new string by using substrings... first substring will be up to the end of your second %3A and the second substring will be from the index of the %2F that comes after it.
Basically, you will be building your string by cutting up the string like so:
"http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A"
"%2Flogin%2Fcallback&client_id=x2.node"
... and appending in whatever port number you are trying to put in.
Hope this helps.
This code should get you what you want:
var strURL = "http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node";
var strNewURL = strURL.substring(0,strURL.indexOf("%3A", strURL.indexOf("%3A", strURL.indexOf("redirect_uri") + 1) + 1) + 3) + "4000" + strURL.substring(strURL.indexOf("%2F",strURL.indexOf("%3A", strURL.indexOf("%3A", strURL.indexOf("redirect_uri") + 1) + 1) + 3));
Split the return string in its parameters:
var parts = req.headers.location.split("&");
then split the parts into fieldname and variable:
var subparts = [];
for (var i = 1; i < parts.length; i++)
subparts[i] = parts[i].split("=");
then check which fieldname equals redirect_uri:
var ret = -1;
for (var i = 0; i < subparts.length; i++)
if (subpart[i][0] == "redirect_uri")
ret = i;
if (ret == -1)
// didnt find redirect_uri, somehow handle this error
now you know which subpart contains the redirect_uri.
Because I dont know which rules your redirect_uri follows I can't tell you how to get the value, thats your task but the problem is isolated to subparts[ret][1]. Thats the string which contains redirect_uri.

Capture URL parameter of a link into an alert box

I want to capture the URL parameter of a link onclick and put the URL parameter in an alert box. For example clicking on the link users.php?user_id=200.
How do I capture the URL parameter "user_id=200"?
I have this script but on click, the alert box appears empty:
$(document).ready(function() {
$('.bluetext').on('click', function(event) {
var url = window.location.search.substring(1);
alert(url);
});
});
$(document).ready(function() {
$('.bluetext').on('click', function(event) {
var url = window.location.href.split("?");
alert(url[1]);
});
});
I am splitting url based on "?" question tag , which leads to "url" variable as an array having two values :
url[0] = "users.php" url[1] = "user_id=200"
And then just accessing url[1] hopes its clear now
Your script is working fine.
If you are trying to get url prameter which are re-written for example,
http://stackoverflow.com/questions/29821832/capture-url-parameter-of-a-link-into-an-alert-box/29822617#29822617
Then ofcourse you will get a blank alert msg. This is only works with non re-written urls. for example, your code will only works with this kind of url. http://stackoverflow.com/questions.php?question_id=29821832 (just for exmaple)
If you're trying to get re-written url's values then you can try following,
var params = window.location.pathname.split('/').slice(1); // ["1", "my-event"]
var first = params[0];
var second = params[1];
console.log(second) // will return "29821832". which is question id of this question.
But if you want to get non re-written url's value then your code is fine.
If you want some specific variable's value then you can try below.
I use this to get value of any variable,
function getVarVal (key) {
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
Call this function as per your requirement. eg.,
$('.bluetext').on('click', function(event) {
alert(getVarVal("user_id"));
});

How to detect image file extension in a string with JavaScript [duplicate]

This question already has answers here:
How can I get file extensions with JavaScript?
(36 answers)
Closed 9 years ago.
I would like to know how can I detect an image in a string with JavaScript. For example, I have an input type text that has the following value, "Hey check this out https://exmaple.com/image.jpg" I want to wrap 'https://exmaple.com/image.jpg' in an tag so it can show the image right away in my site. Thank you, I tried using the split function in JavaScript but I don't know how to detect the image extension in the string.
Use lastIndexOf()
var str = "https://example.com/image.jpg";
var dotIndex = str.lastIndexOf('.');
var ext = str.substring(dotIndex);
Fiddle
You'd probably want to use a regular expression like the following in order to find any image type, and make sure you're not returning other junk that you don't want. E.g.
'https://exmaple.com/image.jpg'.match(/[^/]+(jpg|png|gif)$/)
-> ["image.jpg", "jpg"]
var str = "https://example.com/image.jpg";
var extArray = str.split(".");
var ext = extArray[extArray.length - 1];
Try this.
function searchText(text)
{
var arr = text.match("/(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/");
for (var i=0; i<arr.length; i++)
{
//Make tags where 'arr[i]' is your url.
}
}
HINT: (Please use logic based on your needs)
you have to split string somehow based on your condition and check if the string has . or something
var a = "Hey check this out https://exmaple.com/image.jpg";
var text = a.split(' ');
if text array has your condition then assign to variable filename
if(jQuery.inArray(".", text)!==-1) { //i dont prefer only .
filename = text[jQuery.inArray(".", text)];
}
separate the extension
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}

Change url query string value using jQuery [duplicate]

This question already has answers here:
Updating existing URL querystring values with jQuery
(12 answers)
Closed 9 years ago.
I have an example URL like:
http://domain.com/Documents/?page=1&name=Dave&date=2011-01-01
The query string contains the current page number and two additional filters (name and date).
Using the following URL parser: https://github.com/allmarkedup/purl I am able to access certain parts of the URL such as just the page number.
I'm trying to create a way for a user to be able to type a number into a textbox and then load that page number whilst keeping all the other query strings intact.
$(document).ready(function () {
$('.pageNum').live('keyup', function (e) {
e.preventDefault();
if (e.which == 13) {
var currentUrl = window.location.href;
var parsedUrl = $.url(currentUrl);
var currentPageNum = parsedUrl.param('page');
var newPageNum = $(this).val();
var newUrl = //
window.location.href = newUrl;
}
});
});
So when a user hits return on the pageNum textbox, it will get the current page url, parse it, then find out the current page number and then I need a way to replace the value of the page number with the new value in the textbox to create a new url, and then finally refresh the page using this new url.
Is it possible to change the param value and then add it back in?
Note: The additional parameters could be anything, so I can't manually add them onto the pathname with the new page number!
If you only need to modify the page num you can replace it:
var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);
purls $.params() used without a parameter will give you a key-value object of the parameters.
jQuerys $.param() will build a querystring from the supplied object/array.
var params = parsedUrl.param();
delete params["page"];
var newUrl = "?page=" + $(this).val() + "&" + $.param(params);
Update
I've no idea why I used delete here...
var params = parsedUrl.param();
params["page"] = $(this).val();
var newUrl = "?" + $.param(params);

Categories