Match a string using a regular expression - javascript

I have the following string
name=cvbb&source=Mamma+Mia&startdate=2014-03-24
How can I match the value associated with name with regular expressions, namely the string "cvbb"
/[^name]=[^&]/ matches =cvbb but i want only cvbb

It looks like you want to get URL parameter value? In this case you could use this function :
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var value = getParameterByName('startdate');
That would put 2014-03-24 in a var named value

I am assuming you want to select the name out, right? For that you can use the expression:-
/name=([\w]+)&source=.*/
Explanation: The first word name is written right there. After that ([\w]+) will match a list of alphanumeric characters. Then & will come and stop our selection. If you want to check that the string starts with name then use
/^name=([\w]+)&source=.*/
Caution: Using [^name] means that the characters should not be n,a,m or e which is not what you want to check. I hope this helps.

try
var queryString = 'name=cvbb&source=Mamma+Mia&startdate=2014-03-24';
var theStringImAfter = queryString.match(/[?&]name=([^&]*)/i)[1]
Note that queryString can be a full url e.g. from window.location.href, you don't need to parse the query string first.
If you are passing an encoded string (which is the norm if you are including characters not supported in a url such as a space, ampersand or equal sign etc.) you will want to decode the string before you use it. This can be done with decodeURIComponent(theStringImAfter).
Here is the same approach wrapped up in a reusable function
function getArg(url, arg){
var v=url.match(new RegExp('[?&]' + arg + '=([^&]*)', 'i'));
return (v)?decodeURIComponent(v[1]):'';
}
Usage:
var theStringImAfter = getArg('name=cvbb&source=Mamma+Mia&startdate=2014-03-24', 'name');

Related

Cannot extract parts of a string

I have a string like this : SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:.
Using Javascript, I would like to extract the two IDs (which can be different) : 6E5F5E0D-0CA4-426C-A523-134BA33369D7 and C5DD2ADA-E0C4-4971-961F-233789297FE9.
I'm using this regular expression : ^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$.
I expect this expression to extract into two matching groups the two IDs.
By now, my code is :
var input = "SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:";
var myregex = /^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$/g;
var match = input.match(myregex);
var listId = match[0];
var webId = match[1];
However, this is not working as expected. The first match contains the whole string, and the second match is undefined.
What is the proper way to extract my ID's?
Here is a jsfiddle that illustrate my issue.
This should suit your needs:
var regex = /^SPList:([0-9A-F-]+)[?]SPWeb:([0-9A-F-]+):$/g;
var match = regex.exec(input);
var listId = match[1];
var webId = match[2];
I simply replaced the non-capturing groups of your initial regex by capturing groups, and used regex.exec(input) instead of input.match(regex) to get the captured data. Also, since the IDs seem to be hexadecimal values, I used A-F instead of A-Z.
try this:
var myregex = /[^\:]([0-9A-Z\-]+)[^\?|\:]/g;
var match = input.match(myregex);
alert("listID: " + match[1] + "\n" + "webID: " + match[3]);

Regex for parsing parameters from url

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/

Jquery/Javascript remove duplicate parameters in a url string

Here's my url string, I am trying to break down the parameters and get the value for "q" parameter.
a) http://myserver.com/search?q=bread?topic=14&sort=score
b) http://myserver.com/search?q=bread?topic=14&sort=score&q=cheese
how do i use Jquery/JavaScript to get "q" value?
for case a), i can use string split or use jquery getUrlParam to get q value = bread
for case b), when there are duplicates how do i retrieve the q value at the end, when there are multiple "q" params
in pure javascript, try
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
Reference
in jQuery see this plugin
https://github.com/allmarkedup/jQuery-URL-Parser
UPDATE
when u get array of all query string then to remove duplicate from an array via jQuery try unique or see this plugin
http://plugins.jquery.com/plugin-tags/array-remove-duplicates
Here you can use a regular expression. For example, we might have this string:
var str = 'http://myserver.com/search?q=bread&topic=14&sort=score&q=cheese';
Find the search portion of the URL by stripping everything from the beginning to the first question mark.
var search = str.replace(/^[^?]+\?/, '');
Set up a pattern to capture all q=something.
var pattern = /(^|&)q=([^&]*)/g;
var q = [], match;
And then execute the pattern.
while ((match = pattern.exec(search))) {
q.push(match[2]);
}
After that, q will contain all the q parameters. In this case, [ "bread", "cheese" ].
Then you can use any of q.
If you only care about the last one, you can replace the q.push line with q = match[2].
It looks like you can use getUrlParam for both, but you have to handle the second case's return value as an array with multiple values (at least in the getUrlParam code I'm looking at).
getUrlParam('q') should return an array. Try to get those values with this code:
values = $.getUrlParam('q');
// use the following code
first_q_value = values[0];
second_q_value = values[1];

how do I capture something after something else? like a referer=someString

I have ref=Apple
and my current regex is
var regex = /ref=(.+)/;
var ref = regex.exec(window.location.href);
alert(ref[0]);
but that includes the ref=
now, I also want to stop capturing characters if a & is at the end of the ref param. cause ref may not always be the last param in the url.
You'll want to split the url parameters, rather than using a regular expression.
Something like:
var get = window.location.href.split('?')[1];
var params = get.split('&');
for (p in params) {
var key = params[p].split('=')[0];
var value = params[p].split('=')[1];
if (key == 'ref') {
alert('ref is ' + value);
}
}
Use ref[1] instead.
This accesses what is captured by group 1 in your pattern.
Note that there's almost certainly a better way to do key/value parsing in Javascript than regex.
References
regular-expressions.info/Brackets for Capturing
You are using the ref wrong, you should use ref[1] for the (.+), ref[0] is the whole match.
If & is at the end, modify the regexp to /ref=([^&]+)/, to exclude &s.
Also, make sure you urldecode (unescape in JavaScript) the match.
Capture only word characters and numbers:
var regex = /ref=(\w+)/;
var ref = regex.exec(window.location.href);
alert(ref[1]);
Capture word characters, numbers, - and _:
var regex = /ref=([\w_\-]+)/;
var ref = regex.exec(window.location.href);
alert(ref[1]);
More information about Regular Expressions (the basics)
try this regex pattern ref=(.*?)&
This pattern will match anything after ref= and stop before '&'
To get the value of m just use following code:
var regex = /ref=(.*?)&/;
var ref = regex.exec(window.location.href);
alert(ref[1]);

Extracting number ID from a URL in Javascript

Similar to my previous question:
spliting a string in Javascript
The URLs have now changed and the unique number ID is no longer at the end of the URL like so:
/MarketUpdate/Pricing/9352730/Report
How would i extract the number from this now i cannot use the previous solution?
You could search for
/(\d+)/
and use backreference no. 1 which will contain the number. Note that this requires the number to always be delimited by slashes on both sides. If you also want to match numbers at the end of the string, use
/(\d+)(?:/|$)
In JavaScript:
var myregexp = /\/(\d+)\//;
// var my_other_regexp = /\/(\d+)(?:\/|$)/;
var match = myregexp.exec(subject);
if (match != null) {
result = match[1];
} else {
result = "";
}
If the URLs always look like that, why not use split() ?
var ID = url.split('/')[3];
urlstring = "/MarketUpdate/Pricing/9352730/Report"
$str = urlstring.split("/");
alert($str[3]);
This splits the string each time it finds the / symbol and stores it into an array, You can then get each word in the array by using $str[0]

Categories

Resources