parse extra information in a link with javascript [duplicate] - javascript

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
i have this link output from a facebook feed:
http://l.facebook.com/l.php?u=http%3A%2F%2Fwww.theguardian.com%2Ftravel%2F2014%2Fapr%2F25%2Fitaly-puglia-salento-region&h=2AQF4oNrg&s=1
and i need the final ouput like this:
http://www.theguardian.com/travel/2014/apr/25/italy-puglia-salento-region
so basically i have this bit to remove:
http://l.facebook.com/l.php?u=
i was trying a regex in javascript but not very familiar with it:
Body = document.getElementsByTagName("body")[0].innerHTML;
regex = ???
Matches = regex.exec(Body);
any ideas on how to make it work?

Use this :
function extractLinkFromFb(fbLink) {
var encodedUri = fbLink.split('?u=');
return decodeURIComponent(encodedUri[1]);
}
var link = 'http://l.facebook.com/l.php?u=http%3A%2F%2Fwww.theguardian.com%2Ftravel%2F2014%2Fapr%2F25%2Fitaly-puglia-salento-region&h=2AQF4oNrg&s=1';
var myExtractedLink = extractLinkFromFb(link);
The function extractLinkFromFb() will return your link.

Before decoding the url, you can use this regex to grab the piece you want:
var myregex = /u=([^&#\s]+)/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
thematch = matchArray[1];
} else {
thematch = "";
}
The parentheses in the regex captures the match to Group 1
u= serves as a delimiter, but is not captured in Group 1
[^&#\s] matches one character that is not a &, # or whitespace character. Tweak to suit.
the + quantifier matches one or more of these characters

var url = 'http://l.facebook.com/l.php?u=http%3A%2F%2Fwww.theguardian.com%2Ftravel%2F2014%2Fapr%2F25%2Fitaly-puglia-salento-region&h=2AQF4oNrg&s=1';
var str1 = "http://l.facebook.com/l.php?u=";
var str2 = "&h=2AQF4oNrg&s=1";
var url = url.replace(str1, "");
var url=url.split("&h=")
var uri_dec = decodeURIComponent(url[0]); // =http://www.theguardian.com/travel/2014/apr/25/italy-puglia-salento-region
//alert (uri_dec);
//console.log (uri_dec);

Related

Javascript - split values inside parentheses [duplicate]

This question already has answers here:
How to get function parameter names/values dynamically?
(34 answers)
Closed 3 years ago.
I am trying to split the following string:
delete(value1,value2);
I want to get the values and save them in a array:
var values = [value1,value2]
A regex would do the trick:
/\((.*)\)/g.exec('delete(value1,value2);')[1].split(',')
This captures anything between parentheses, which you can then split again.
You can split the string using split function
var str = "delete(value1,value2)";
var stringArray = str.split("(");
var values=stringArray[1].split(",");
use Replace method to finally delte ")" from second string in array
values[1]=values[1].replace(")","");
How about:
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(fnStr) {
var fnStr = fnStr.replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if(result === null)
result = [];
return result;
}
var str = "delete(value1,value2)";
getParamNames(str);

How can i get all clean links via Regex without pattern string [duplicate]

This question already has answers here:
How do you access the matched groups in a JavaScript regular expression?
(23 answers)
Closed 4 years ago.
when i trying this match im getting links like this;
Result:
"video","src":"https:\/\/video-mxp1-1.xx.fbcdn.net\/v\/t42.9040-2\/34384597_178997956146914_227512178675023872_n.mp4"
I want get just cleaned link like this:https:\/\/video-mxp1-1.xx.fbcdn.net\/v\/t42.9040-2\/34384597_178997956146914_227512178675023872_n.mp4
Thanks for your helps;
My codes are below:
var VideoLinks='"type":"video","src":"https:\\\/\\\/video-mxp1-1.xx.fbcdn.net\\\/v\\\/t42.9040-2\\\/34333324_n.mp4?_nc_cat=0&efg=ey1&oe=5B211DB0","width":null"type":"video","src":"https:\\\/\\\/video-mxp1-1.xx.fbcdn.net\\\/v\\\/t42.9040-2\\\/34333324_n.mp4?_nc_cat=0&efg=ey1&oe=5B211DB0","width":null';
My Pattern
pattern =/"video","src":"(.*?)"/g;
var videos=Sitestring.match(pattern);
console.log(videos);
const str = '"video","src":"https:\vid1.mp4"';
const regex = new RegExp('src\":\"(.*)\"', 'i');
console.log(regex.exec(str)[1]);
And about multiple occurences
function getMatch(str, regex) {
const matches = [];
let oneMatch;
do {
oneMatch = regex.exec(str);
if (!oneMatch) {
return matches;
}
matches.push(oneMatch[1]);
} while (oneMatch);
}
const str = '"video","src":"https:vid1.mp4","video","src":"https:vid2.mp4","video","src":"https:vid3.mp4"';
const regex = new RegExp('src\":\"(.*?)\"', 'ig');
console.log(getMatch(str, regex));

Javascript RegEx to find string in url between slash and either comma or question mark

I'd like to have javascript return value of 'sct' or 'rain' (strip the ",20" or ",70") from urls like:
<script>
var urls = [
"https://api.weather.gov/icons/land/day/sct,20?size=medium",
"https://api.weather.gov/icons/land/day/sct?size=medium",
"https://api.weather.gov/icons/land/night/rain?size=medium",
"https://api.weather.gov/icons/land/day/rain,60/rain,70?size=medium"
];
for(var key in urls) {
console.log(get_icon(urls[key]));
}
function get_icon(text) {
/* not sure what to do here */
}
</script>
The logic would be get string after last slash and before comma or question mark. I'm struggling with the regex statement to do that.
You can use this regex with a greedy match of .* to make sure last / is matched:
/.*\/([^,?]+)/
RegEx Demo
([^,?]+) gives you string before next ? or , in a capturing group.
Code:
var urls = [
"https://api.weather.gov/icons/land/day/sct,20?size=medium",
"https://api.weather.gov/icons/land/day/sct?size=medium",
"https://api.weather.gov/icons/land/night/rain?size=medium",
"https://api.weather.gov/icons/land/day/rain,60/rain,70?size=medium"
];
for(var key in urls) {
console.log(get_icon(urls[key]));
}
function get_icon(text) {
return (text.match(/.*\/([^,?]+)/) || [null][null])[1];
}
Please check this regex. Extract group 1 :
\S+\/(\w+,\d+|\w+)\?\w+=\w+
Reply on your need, I can do:
function get_icon(text) {
var pos = text.lastIndexOf("/");
var qmark = text.lastIndexOf("?size");
var res = text.substring(pos+1, qmark);
var res = res.split(",");
if (res.length == 2)
return res[1];
else
return null;
}

JavaScript regular expression for two-letter tokens separated by commas

I am trying to get the regular expression that accepts only characters with specific pattern like two characters separated by comma, but I am not able to get it.
Here i included the acceptable sting
string = ab,ca,ls,gz,tv......
I tried:
/^([a-zA-Z]{2},)|([a-zA-Z]{2})*$/
but it is not working as expected.
Try using /^[a-z]{2}(?:,[a-z]{2})*$/i instead (the | inside your pattern was problematic):
var string = 'ab,ca,ls,gz,tv'
var regex = /^[a-z]{2}(?:,[a-z]{2})*$/i
console.log(regex.test(string)) //=> true
If I'm understanding you correctly, then you're trying to get (capture) the 2 characters, with the condition that they're within the bounds of a comma or at the start or end of a line:
(?:^|,)([a-zA-Z]{2})(?=,|$)
Live preview
var string = "ab,ca,ls,gz,tv";
const regex = /(?:^|,)([a-zA-Z]{2})(?=,|$)/g;
match = regex.exec(string);
while (match != null) {
console.log(match[1]);
match = regex.exec(string);
}
The above outputs:
ab
ca
ls
gz
tv
Try this.
/^[a-z]{2}(,[a-z]{2})*$/i
var string1 = "ab,ca,ls,gz,tv"
var string2 = "ab,c,ls"
var string3 = "ab,ca"
var regex = /^[a-z]{2}(,[a-z]{2})*$/i
document.getElementById("test").innerHTML =
regex.test(string1) + "<br>" + // true
regex.test(string2) + "<br>" + // false
regex.test(string3) // true
<p id="test"></p>

Javascript Regular Expression multiple match [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
I'm trying to use javascript to do a regular expression on a url (window.location.href) that has query string parameters and cannot figure out how to do it. In my case, there is a query string parameter can repeat itself; for example "quality", so here I'm trying to match "quality=" to get an array with the 4 values (tall, dark, green eyes, handsome):
http://www.acme.com/default.html?id=27&quality=tall&quality=dark&quality=green eyes&quality=handsome
You can use a regex to do this.
var qualityRegex = /(?:^|[&;])quality=([^&;]+)/g,
matches,
qualities = [];
while (matches = qualityRegex.exec(window.location.search)) {
qualities.push(decodeURIComponent(matches[1]));
}
jsFiddle.
The qualities will be in qualities.
A slight variation of #alex 's answer for those who want to be able to match non-predetermined parameter names in the url.
var getUrlValue = function(name, url) {
var valuesRegex = new RegExp('(?:^|[&;?])' + name + '=([^&;?]+)', 'g')
var matches;
var values = [];
while (matches = valuesRegex.exec(url)) {
values.push(decodeURIComponent(matches[1]));
}
return values;
}
var url = 'http://www.somedomain.com?id=12&names=bill&names=bob&names=sally';
// ["bill", "bob", "sally"]
var results = getUrlValue('names', url);
jsFiddle

Categories