Javascript Regular Expression multiple match [duplicate] - javascript

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

Related

Extract words from a string and split [duplicate]

This question already has answers here:
Extract words with RegEx
(3 answers)
Closed 3 years ago.
I have a question. I have a very long string that also contain special characters. I want to use regex to extract the words and use the split function to get the desired output.
["one", "two", "three", "four", "five"]
I've tried this two different approaches.
var fill = "|#!../::one:://::two:://::three:://four:://five|".match("([0-9a-zA-Z_]").split(" ");
var fill = "|#!../::one:://::two:://::three:://four:://five|".toString().split(" "), function(a) { return /[0-9a-zA-Z_]/.test(a)};
.match(...).split is not a function
I'm error message I'm receiving. Any help would be appreciated.
What you want is to get all matches. That can be done via exec() method of RegExp:
const matchWords = /[a-z0-9_]+/gi;
const results = [];
const testStr = "|#!../::one:://::two:://::three:://four:://five|";
let match = null;
while(match = matchWords.exec(testStr)) {
results.push(match[0]);
}
console.log(results);
To see why and how it works, see MDN docs on RegExp.

pass variable to replace function regular expression javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I want to have a 'newline'-function to pass a string to it and print it on pdf. my function so far is
var array = new Array();
function newLineFunction_PDF(text) {
var arr = text.replace(/.{70}\S*\s+/g, "$&#").split(/\s+#/);
return arr;
}
array = newLineFunction_PDF('some Text');
for( var i in array) {
print(array[i]);
}
What it does is cut the text in to pieces of length-70 incl. the last word, push it into the array and print it afterwards with new lines. Now i want to pass a number to the function, like 100, so i can decide the max-length of the text per line.
So far I tried:
function newLineFunction_PDF(text, num) {
var re = new RegExp(/.{num}\S*\s+/g);
var arr = text.replace(re, "$&#").split(/\s+#/);
return arr;
}
but I dont know how and where to add escapes into the new RegExp.
The parameter of Regexp is a string:
var re = new RegExp('.{' + num + '}\S*\s+', 'g');

Javascript get the string between two symbols [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I have the following string and I'm trying to retrieve the string between two symbols
http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats
I need to retrieve wpv-women-clothing[] or any other string between the last & and the last = in the URL
Should I use regex for this or is there a function in Javascript/jQuery already well suited for this?
Thanks
var str = "http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats";
var last =str.split('&').pop().split('=')
console.log(last[0]) // wpv-women-clothing[]
jsFiddle example
Split the string on the ampersands (.split('&')), take the last one (.pop()), then split again on the = (.split('=')) and use the first result last[0].
.*&(.*?)=.*
This should do it.
See demo.
http://regex101.com/r/lZ5bT3/1
Group index 1 contains your desired output,
\&([^=]*)(?==[^&=]*$)
DEMO
> var re = /\&([^=]*)(?==[^&=]*$)/g;
undefined
> while ((m = re.exec(str)) != null) {
... console.log(m[1]);
... }
wpv_post_search&wpv-women-clothing[]
Can you try:
var String = "some text";
String = $("<div />").html(String).text();
$("#TheDiv").append(String);

parse extra information in a link with javascript [duplicate]

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);

RegEx extract all real numbers from a string [duplicate]

This question already has answers here:
Regex exec only returning first match [duplicate]
(3 answers)
Closed 8 years ago.
This regex in JavaScript is returning only the first real number from a given string, where I expect an array of two, as I am using /g. Where is my mistake?
/[-+]?[0-9]*\.?[0-9]+/g.exec("-8.075090 -35.893450( descr)")
returns:
["-8.075090"]
Try this code:
var input = "-8.075090 -35.893450( descr)";
var ptrn = /[-+]?[0-9]*\.?[0-9]+/g;
var match;
while ((match = ptrn.exec(input)) != null) {
alert(match);
}
Demo
http://jsfiddle.net/kCm4z/
Discussion
The exec method only returns the first match. It must be called repeatedly until it returns null for gettting all matches.
Alternatively, the regex can be written like this:
/[-+]?\d*\.?\d+/g
String.prototype.match gives you all matches:
var r = /[-+]?[0-9]*\.?[0-9]+/g
var s = "-8.075090 -35.893450( descr)"
console.log(s.match(r))
//=> ["-8.075090", "-35.893450"]

Categories