I need to strip out the IDs of embedded youtube videos, so I have the url which is something like:
www.youtube.com/embed/[someID]&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1
All I want is the [someID] string. I have declared an empty array to store the regex matches;
var videoID = [];
The closest I have come to a solution is:
videoID = videoID.match("embed/(\w*)");
but this results in the following:
video[0] ("embed/")
video[1] ()
Use this:
url = "www.youtube.com/embed/someID&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1";
Then use either:
var videoID = url.match(/embed\/(\w*)/); // regex
OR else:
var videoID = url.match("embed/\\w*)"); // regex object
Both will give this output:
["embed/someID", "someID"]
If you provide a string then String#match method will attempt to construct a RegExp object and for that case you need to use \\w instead of \w.
Try this you may get id. I didn't use regex but still we can get id from above demo like urls.
var url ="www.youtube.com/embed/[someID]&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1";
var urlQueries = url.split('/');
var queryParameters = urlQueries[2].split('&'); // arrays of all query parameters
var id = queryParameters[0]; // get ids at index 0
Working demo here
I'm not sure if jquery can do Positive-Lookbehinds, but try this (?<=embed\/)([^&]*)
If not, then (?:embed\/)([^&]*) is closer to your example.
Demo:
http://regex101.com/r/nW5uL8
Related
This should be very simple (when you know the answer). From this question
I want to give the posted solution a try. My question is:
How to get the parameter value of a given URL using JavaScript regular expressions?
I have:
http://www.youtube.com/watch?v=Ahg6qcgoay4
I need:
Ahg6qcgoay4
I tried:
http://www.youtube.com/watch\\?v=(w{11})
But: I suck...
You almost had it, just need to escape special regex chars:
regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;
url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'
Edit: Fix for regex by soupagain.
Why dont you take the string and split it
Example on the url
var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"
you can do a split as
var params = url.split("?")[1].split("&");
You will get array of strings with params as name value pairs with "=" as the delimiter.
Not tested but this should work:
/\?v=([a-z0-9\-]+)\&?/i
v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk
In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString
HttpUtility.ParseQueryString(url)["v"];
And you don't even need to check the key, as it will return null if the key is not in the collection.
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
DEMO
I use seperate custom functions which gets all URL Parameters and URL parts .
For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The above function will return an array consisting of url variables.
For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b
I use a simple uri split,
function getUrlParams() {
var vars = {};
var parts = window.location.href.split('/' );
return parts;
}
You can even combine them both to be able to use with a single call in a page or in javascript.
I have this part of a function which is running perfectly:
if(/https?:\/\/[a-z]{2}w?\.mywebsite\./.test(href)){
if(!firstSerp){
firstSerp = this;
add_prerender(this, href);
}
}
As you can see mywebsite is hard-coded. What I want is to put a variable there instead.
So it would look like this:
var mylink = 'mywebsite';
if(/https?:\/\/[a-z]{2}w?\.+= mylink\./.test(href)){}
One of the users suggested I look at How do you use a variable in a regular expression?
var replace = "regex";
var re = new RegExp(replace,"g");
But I have difficulties understanding how that would apply to my example.
Could you please help me solve this?
Regular expressions are intended to be used to check if an existing string matches a pattern or to find a pattern in an existing string. You cannot use them to build a string.
Instead, you should use string concatenation:
const url = 'http://www.' + mywebsite + '.com';
or a string template:
const url = `http://www.${mywebsite}.com`;
I need to parse a complex URL string to fetch specific values.
From the following URL string:
/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss
I need to extract this result in array format:
['http://any-feed-url-a.com?filter=hot&format=rss', 'http://any-feed-url-b.com?filter=rising&format=rss']
I tried already with this one /url=([^&]+)/ but I can't capture all correctly all the query parameters. And I would like to omit the url=.
RegExr link
Thanks in advance.
This regex works for me: url=([a-z:/.?=-]+&[a-z=]+)
also, you can test this: /http(s)?://([a-z-.?=&])+&/g
const string = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&url=http://any-feed-url.com?filter=latest&format=rss'
const string2 = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&next=parm&url=http://any-feed-url.com?filter=latest&format=rss'
const regex = /url=([a-z:/.?=-]+&[a-z=]+)/g;
const regex2 = /http(s)?:\/\/([a-z-.?=&])+&/g;
console.log(string.match(regex))
console.log(string2.match(regex2))
have you tried to use split method ? instead of using regex.
const urlsArr = "/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss".split("url=");
urlsArr.shift(); // removing first item from array -> "/api/rss/feeds?"
console.log(urlsArr)
)
which is going to return ["/api/rss/feeds?", "http://any-feed-url-a.com?filter=hot&format=rss&", "http://any-feed-url-b.com?filter=rising&format=rss"] then i am dropping first item in array
if possible its better to use something else then regex CoddingHorror: regular-expressions-now-you-have-two-problems
You can matchAll the url's, then map the capture group 1 to an array.
str = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss'
arr = [...str.matchAll(/url=(.*?)(?=&url=|$)/g)].map(x => x[1])
console.log(arr)
But matchAll isn't supported by older browsers.
But looping an exec to fill an array works also.
str = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss'
re = /url=(.*?)(?=&url=|$)/g;
arr = [];
while (m = re.exec(str)) {
arr.push(m[1]);
}
console.log(arr)
If your input is better-formed in reality than shown in the question and you’re targeting a modern JavaScript environment, there’s URL/URLSearchParams:
const input = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot%26format=rss&url=http://any-feed-url-b.com?filter=rising%26format=rss';
const url = new URL(input, 'http://example.com/');
console.log(url.searchParams.getAll('url'));
Notice how & has to be escaped as %26 for it to make sense.
Without this input in a standard form, it’s not clear which rules of URLs are still on the table.
I have a string which has email id as plain text in it ,I want to replace the email id in the string with hashed value eg.
var str ="Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB"
Before storing the above string I want to hash only testmail5#gmail.com which is after userId=. Hence need suggestions to achieve the same.
Using split twice
var str="Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB"
console.log(str.split('userId=')[1].split('|')[0])
Try this :
str.match(/\userId=(.*?)\|/)[1]
Regex are better to do stuff like that
Quick and dirty way by using URL API in JS.
var data = "Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB";
var some_hash = "myHashValue";
var data_url = new URL("http://localhost/?"+data); // dirty part
var new_data = data.replace(data_url.searchParams.get("userId").split('|')[0], some_hash);
console.log(new_data);
I am using a regular expression to capture a URL string, but it's not working out.
Here's my code, which is coming from an external JavaScript document, linked to the HTML file:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch);
The output that I get is this: "www.google.com,www.,,www."
What am I doing wrong?
Thanks! :)
Your regex works fine, what happens is that according to the match function you are getting one extra result for each group (defined by these parenthesis) that you have in your regex. to access the whole match you can access to the first item of the match return like the following:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx)[0]; //this line changed, im using [0] to access the whole match only
document.write(urlRegMatch);
working example: https://jsfiddle.net/2sptg5rz/3/
reference about the match function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Return_value
I'd like to thank #Dknacht and #Tressa for directing me to the correct answer, since the first value of the array, 0, is the matched text.
This code works for what I want to do:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch[0]);