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/
Related
This question already has answers here:
String manipulation - getting value after the last position of a char
(8 answers)
Closed 5 years ago.
I have this RegExp below working. But the return is True or False. What I want here is to get the last DOT of a string and return the last string after the DOT. As example below I have image.jpeg.jpeg I want to return the last jpeg. I also try g.match(x) but it gives me an error. g.match is not a function
var x = "image.jpeg.jpeg"
var g = /(.*)\.(.+)/;
alert(g.test(x));
Alternatively, you can use split method like so:
var x = "image.jpeg.jpeg";
var ans = x.split('.').pop();
console.log(ans);
Try this:
var x = "image.jpeg.jpeg"
var g = /(.*)\.(.+)/;
alert(x.match(g)[2]);
match is a method of String (not RegExp), it's argiment RegExp
Try this:
var matches = x.match(g);
if (matches.length === 0) {
console.log('Error');
return;
}
var last = m[m.length - 1]
alert(last);
use this:
var x = "image.jpeg.jpeg"
var g = /\.([0-9a-z]+)$/i;
console.log(x.match(g)[0]); //with a dot
console.log(x.match(g)[1]); //extension only
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');
This question already has answers here:
Remove everything after last backslash
(3 answers)
Closed 9 months ago.
Okay I have this
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(URL.lastIndexOf("/")));
Gives you "/remove-everything-before-the-last-occurrence-of-a-character"
How do I get "http://stackoverflow.com/questions/10767815/"
Here you are:
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
alert(URL.substring(0, URL.lastIndexOf("/") + 1));
Hope this helps.
Seems like a good case for a regular expression (can't believe no one has posted it yet):
URL.replace(/[^\/]+$/,'')
Removes all sequential non–forward slash characters to the end of the string (i.e. everything after the last /).
Generic solution
This is a generic function that also handles the edge case when the searched character or string (needle) is not found in the string we are searching in (haystack). It returns the original string in that case.
function trimStringAfter(haystack, needle) {
const lastIndex = haystack.lastIndexOf(needle)
return haystack.substring(0, lastIndex === -1 ? haystack.length : lastIndex + 1)
}
console.log(trimStringAfter('abcd/abcd/efg/ggfbf', '/')) // abcd/abcd/efg/
console.log(trimStringAfter('abcd/abcd/abcd', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd/', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd', '/')) // abcd/
console.log(trimStringAfter('abcd', '/')) // abcd
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(0,URL.lastIndexOf('/')+1));
//The +1 is to add the last slash
Try this jsfiddle or run the code snippet.
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var myRegexp = /^(.*\/)/g;
var match = myRegexp.exec(URL);
alert(match[1]);
console.log(URL.substring(0, URL.lastIndexOf("/")+1));
Run this:
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var temp = URL.split('/');
temp.pop();
var result = temp.join('/');
alert(result);
Try utilizing .match() with RegExp /^\w+.*\d+\//
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var res = URL.match(/^\w+.*\d+\//)[0];
document.body.textContent = res;
Try an array based extraction like
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
snippet.log(URL.split('/').slice(0, 5).join('/'));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 8 years ago.
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and : colon but, js's split function only supports one separator.
Example :
materialA:125,materialB:150,materialC:175
I want to split both these values into array like
materiaA,materialB,materialC
and second
125,150,175
Or anybody can give me idea how could I multiply these numbers with a constant to get like
materialA:1250, materialB:1500,materialC:1750.
You can split with more than one seperator if you're using regex:
.split(/:|,/)
This would give
["materialA", "125", "materialB", "150", "materialC", "175"]
Changing the approach completely, if all you want to do is multiply all the numbers in your string by a fixed coefficient, you can use string.replace:
var string = "materialA:125,materialB:150,materialC:175";
var coef = 10;
var result = string.replace(/\d+/g, function(match){
return parseInt(match)*coef;
});
Then print(result) outputs the string
materialA:1250,materialB:1500,materialC:1750
\d is a shortcut for [0-9].
Example using #mitim's method:
var str = 'materialA:125,materialB:150,materialC:175',
multiplier = 2;
str = str.split(',').map(function (elem) {
var parts = elem.split(':');
parts[1] *= multiplier;
return parts.join(':');
}).join(',');
This will give you:
materialA:250,materialB:300,materialC:350
You could split the string by comma first, then loop through the resulting array. In that array, each entry would be something like "materialA:125". From there, you can split by the colon and append each part to its own list to work with or if you prefer, just multiply the second half (cast to int first) and rejoin it in to your original string.
Even though someone gave a much better answer, here's a bit of code that does what I mentioned above (since you asked)
var inputString = "materialA:125,materialB:150,materialC:175";
var mats = new Array();
var numbers = new Array();
var temp;
var elements = inputString.split(",");
for(var element in elements){
temp = elements[element].split(":");
mats.push(temp[0]);
numbers.push(parseInt(temp[1]));
}
console.log(mats); // prints ["materialA", "materialB", "materialC"]
console.log(numbers); // prints [125, 150, 175]
You could simply use following Regex:
/[:,]/
And following string method:
mystring = 'materialA:125,materialB:150,materialC:175';
result = mystring.split(/[:,]/);
Here is a Fiddle.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get query string values in JavaScript
If one submits a GET form, the resulting address will look like www.example.com/stuff?param1=stuff¶m2=morestuff. I know how to read/set the value of a form field on a page, but how do I read submissions from the previous page (in the URL) with JavaScript? I guess I could take the url and split() it, to get the parameters, but is there any quicker/simpler way to read param1 (just an example)?
Note: this is not a duplicate of this, since that question is about how to do it in PHP.
function getQuerystring(key)
{
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,\\\]);
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs != null)
return(qs[1]);
else
return("");
}
No, there's no simple way to do that.
Use something like this:
var qstring = {}, src = location.search.substring(1).split("&");
for (var i = 0; i < src.length; i++) {
var parts = src[i].split("=");
qstring[unescape(parts[0])] = unescape(parts.slice(1).join("="));
}
Now the object qstring is a key/value map of the query string. Keep in mind that values with the same key are overwritten, so you may want to store them in an indexed array instead of an associative array.
I think this topic is answer to your question.
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
You can try also this one
jQuery URL Parser Plugin. In case you want to use jQuery.
jsUri. In case jQuery is too heavy for you.