Get image name out of image address with JavaScript [duplicate] - javascript

This question already has answers here:
How to pull the file name from a url using javascript/jquery?
(16 answers)
Closed 9 years ago.
I would like to get the image name out of the address.
This is the value I with the JavaScript:
http://localhost:51557/img/column-sortable.png
document.getElementById("ctl00_contentHolder_iSortColumn").value = columnNumber;
alert(imageName);
Whats the best way to get column-sortable.png out of the string?

As long as there's never anything after the image name in the URL (no query string or hash) then the following should work:
var str = "http://localhost:51557/img/column-sortable.png";
alert(str.substring(str.lastIndexOf('/') + 1));

Please refer to the split function:
var url = http://localhost:51557/img/column-sortable.png;
var elementArray = url.split('/');
var imageName = elementArray[elementArray.length - 1];
JSFiddle

If you want to try using Regex, check this out.
var imgURL = "http://localhost:51557/img/column-sortable.png";
var imageName = imgURL.replace( /^.*?([^/]+\..+?)$/, '$1' );
alert(imageName);

Related

How to parse url to get desired value [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
How can I parse a link in jqueryjavascript?
I have the url (some path)/restaurantProfile.php?id=51
And I want to parse this to only obtain the 51. (keep in mind this needs to be generalized. The id won't obviously be always 51...)
Thanks in advance!
You can split the string at id=:
var url = 'some/path/restaurantProfile.php?id=51';
var id = url.split('id=')[1]; // 51
I forget where I saw this, but here is a nice jquery function you can use for this:
//jQuery extension below allows for easy query-param lookup
(function($) {
$.QueryString = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
Usage like so:
var restaurantId = $.QueryString["id"];
You can make use of Regular Expression in javascript. RegExp Object provides methods to Match the Regular Expression with a input String.
You can make use of string object split method to split the string by using a separator character.
There is a similar question at How can I get query string values in JavaScript? for more options.
You can use the URLSearchParams API to work with the query string of a URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
// get the current url from the browser
var x = new URLSearchParams(window.location.search);
// get the id query param
var id = x.get('id');

How can I do string replace in jquery [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I have this code
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(" ", "-");
$("#newsurl").val(res);
});
to replace spaces into dash to get URL like this
wordone-wordtow-wordthree
but i have problem with this code it's just replace first space like this
wordone-wordtow wordthree
How can i solve this problem
You need to do a global match, you can do this with a regex
var res = titleval.replace(/\s/g, "-");
Though String.prototype.replace does support having flags passed, this is deprecated in firefox and already doesn't work in chrome/v8.
Alternate method (if regex is not mandatory) could be to split and join
var res = titleval.split(" ").join("-");
or
var res = titleval.split(/\s+/).join("-");
Use regex with global flag
titleval.replace(/\s/g, "-");
try like this:
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(/\s+/g, '-');
$("#newsurl").val(res);
});

Split URL string to get each parameter value in javascript [duplicate]

This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 8 years ago.
var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC"
How can I split the string above so that I get each parameter's value??
You could use the split function to extract the parameter pairs. First trim the stuff before and including the ?, then split the & and after that loop though that and split the =.
var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var queryparams = url.split('?')[1];
var params = queryparams.split('&');
var pair = null,
data = [];
params.forEach(function(d) {
pair = d.split('=');
data.push({key: pair[0], value: pair[1]});
});
See jsfiddle
Try this:
var myurl = "journey?reference=123&line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var keyval = myurl.split('?')[1].split('&');
for(var x=0,y=keyval.length; x<y; x+=1)
console.log(keyval[x], keyval[x].split('=')[0], keyval[x].split('=')[1]);
to split line in JS u should use:
var location = location.href.split('&');

Extracting a URL parameter with JavaScript [duplicate]

This question already has answers here:
Get escaped URL parameter
(19 answers)
Closed 8 years ago.
I have a URL:
http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382
Edit: I should also not the url is stored in a variable and I want it to work something like this:
$(".videothumb a").live('click', function() {
var URL = < do something to cut the string >
console.log(URL);
return false;
});
And I want to cut the URL starting from "=" and ending at "&" so I'll end up with a string like this: "JssO4oLBm2s".
I only know of the slice() function but I believe that only takes a number as beginning and end points.
Using .split() will give a position based solution which will fail the order of parameters changes. Instead I think what you are looking for is the value of parameter called v for that you can use a simple regex like
'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'.match('[?&]v=(.*?)(&|$)')[1]
Try
'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'
.split('=')[1] // 'JssO4oLBm2s&list'
.split('&')[0] // 'JssO4oLBm2s'
Or, if you want to be sure to get the v parameter,
var v, args = 'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'.split("?")[1].split('&');
for(var i = args.length-1; i>=0; --i) {
var data = args[i].split('=');
if(data[0]==='v') { v = data[1]; break; }
}
Use .split(). Separated to 2 lines for clarity
var first = "http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382".split('=')[1]
var result = first.split('&')[0]; //result - JssO4oLBm2s
v = 'JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382';
var vamploc = v.indexOf("&");
vstring = v.substr(0, vamploc);
You can play with the code a bit to refine it, but the general concepts work.
use Regexp (?:v=)(.+?)(?:&|$)
Fiddle DEMO
"http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382".match('(?:v=)(.+?)(?:&|$)')[1]
Reference
http://gskinner.com/RegExr/

Getting a number from within a URL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I get query string values?
I am trying to get a page number from a URL during a test. The URL looks like this:
http://www.site.com/objects/search/8765XX/results?page=2&sort_att=posted_dt&sort_dir=desc
What I want to get is the page number right after 'page=' in the url.
In one line, by splitting url. jsfiddle
var url = "http://www.site.com/objects/search/8765XX/results?page=2&sort_att=posted_dt&sort_dir=desc";
var pageNumber = parseInt(url.split("page=")[1].split("&")[0], 10);
A simple pure JavaScript implementation I can think of would be something like the following:
var url = http://www.site.com/objects/search/8765XX/results?page=2&sort_att=posted_dt&sort_dir=desc
var matchedPos = url.search("page=\\d");
var matched = url.substr(matchedPos);
var num = matched.split("=")[1]; //might need to parse
I have this small function to fetch URL parameters (I found it on internet many years ago) :
function getUrlParameter(name, defaultValue) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return defaultValue;
else return results[1];
}
I use it like this :
pageNumber = parseInt(getUrlParameter('page'), 10);

Categories

Resources