I am trying to extract ?ref value from a URL and wanted to replace it with some other value.
Example Lets say my URL is something like this http://myexample.com/?ref=test?nref=xml&page=1 or it can be http://myexample.com/?fref=like?ref=test?nref=xml&page=1
From the above url I wanted to find ?ref value and wanted to replace it from another string say "testing". Any help and also wanted to learn advance Regular expressions any help.
Thanks in advance.
A solution for your posted examples.
str = str.replace(/\b(ref=)[^&?]*/i, '$1testing');
Regular expression:
\b the boundary between a word char (\w) and and not a word char
( group and capture to \1:
ref= 'ref='
) end of \1
[^&?]* any character except: '&', '?' (0 or more times)
The i modifier is used for case-insensitive matching.
See working demo
Make sure you don't have two "?" in url. I assume you mean
http://myexample.com?ref=test&nref=xml&page=1
you can use the function below
here url is your url, name is the key, in your case it is "ref", and the new_value is the new value, i.e. the value that would replace "test"
the function will return the new url
function replaceURLParam (url, name, new_value) {
// ? or &, name=, anything that is not &, zero or more times
var str_exp = "[\?&]" + name + "=[^&]{0,}";
var reExp = new RegExp (str_exp, "");
if (reExp.exec (url) == null) { // parameter not found
var q_or_a = (url.indexOf ("?") == -1) ? "?" : "&"; // ? or &, if url has ?, use &
return url + q_or_a + name + "=" + new_value;
}
var found_string = reExp.exec (url) [0];
// found_string.substring (0, 1) is ? or &
return url.replace (reExp, found_string.substring (0, 1) + name + "=" + new_value);
}
Try this :
var name = 'ref',
value = 'testing',
url;
url = location.href.replace(
new RegExp('(\\?|&)(' + name + '=)[^&]*'),
'$1$2' + value
);
new RegExp('(\\?|&)(' + name + '=)[^&]*') gives /(\?|&)(ref=)[^&]*/ which means :
"?" or "&" then "ref=" then "everything but '&' zero or more times".
Finally, $1 holds the result of (\?|&) while $2 holds the result of (ref=).
Links to read : replace, regexp.
Related
I find it hard to believe this hasn't been asked but I can find no references anywhere. I need to add a URI hash fragment and update the value if it already is in the hash. I can currently get it to add the hash but my regex doesn't appear to catch if it exists so it adds another instead of updating.
setQueryString : function() {
var value = currentPage;
var uri = window.location.hash;
var key = "page";
var re = new RegExp("([#&])" + key + "=.*#(&|$)", "i");
var separator = uri.indexOf('#') !== -1 ? "&" : "#";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
},
Also if this can be made any cleaner while preserving other url values/hashes that would be great.
example input as requested
Starting uri value:
www.example.com#page=1 (or no #page at all)
then on click of "next page" setQueryString gets called so the values would equal:
var value = 2;
var uri = '#page1'
var key = 'page'
So the hopeful output would be '#page2'.
As to your regex question, testing if the pattern #page=(number) or &page=(number) is present combined with capturing the number, can be done with the regex /[#&]page\=(\d*)/ and the .match(regex) method. Note that = needs escaping in regexes.
If the pattern exists in the string, result will contain an array with the integer (as a string) at result[1]. If the pattern does not exist, result will be null.
//match #page=(integer) or &page=(integer)
var test = "#foo=bar&page=1";
var regex = /[#&]page\=(\d*)/;
var result = test.match(regex);
console.log(result);
If you want to dynamically set the key= to something other than "page", you could build the regex dynamically, like the following (note that backslashes needs escaping in strings, making the code a bit more convoluted):
//dynamically created regex
var test = "#foo=bar&page=1";
var key = "page"
var regex = new RegExp("[#&]" + key + "\\=(\\d*)");
var result = test.match(regex);
console.log(result);
I need to make a specific regex for something like this:
(\d{1,3}\/\d{1,3}\/\d{1,3})\-(.*)
example:
1/2/3-abc
It accepts:
1/2/3 - capture index 1
and abc - capture index 2
I need from capture index 1 just 123 without '/' characters.
I tried it with positive/ negative lookahead, but it won't work.
Many Thanks
You can achieve what you need with some string operations:
var s = "1/2/3-abc";
if (s.indexOf("-") > -1) { // Check if there is a hyphen in the string
document.write( s.substring(0, s.indexOf("-")).replace(/\//g, ""));
}
The s.indexOf("-") will find the index of the first - character in the input string, and after we get the substring from the start till the - (with s.substring(0, s.indexOf("-"))), we can remove the / symbols with .replace(/\//g, "").
You cannot extract characters out of an individual match. You need to capture the whole group. After that, you can replace the characters you do not want.
You can extract the group using a matcher or a replacer.
function processMatcher(str) {
var match = str.match(/(\d{1,3}\/\d{1,3}\/\d{1,3})\-(.*)/);
return match[1].replace(/[\/]/g, '');
}
function processReplacer(str) {
return str.replace(/(\d{1,3}\/\d{1,3}\/\d{1,3})\-(.*)/, function(match, p1, p2, offset, string) {
return p1.replace(/[\/]/g, '');
});
}
document.body.innerHTML = 'Matcher: ' + processMatcher('1/2/3-abc') + '</br />';
document.body.innerHTML += 'Replacer: ' + processReplacer('1/2/3-abc');
Below I'm trying to replace the moduleName string with another string replacementModule.
var replacementModule = 'lodash.string' // cheeky
var moduleName = 'underscore.string'
var pattern = new RegExp('^' + moduleName + '(.+)?')
var match = definition.match(pattern)
var outcome = replacementModule + match[1]
However right now a totally different module is matched as well.
underscore.string.f/utils // desired no change
underscore.string.f // desired no change
underscore.string // => lodash.string
underscore.string/utils // => lodash.string/utils
How can I match to the /, and how the outcome that I expect?
You need to do at least 3 things:
Escape the string variable passed to the RegExp
Check if match is null before using it
The regex should contain ($|/.*) as capturing group 1 to match either an end of string or / followed by 0 or more characters.
RegExp.escape = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
function runRepl(definition, replacementModule, moduleName) {
var pattern = RegExp('^' + RegExp.escape(moduleName) + '($|/.*)');
// ^------------^ ^------^
var match = definition.match(pattern);
if (match !== null) { // Check if we have a match
var outcome = replacementModule + match[1];
document.write(outcome + "<br/>");
}
else {
document.write("N/A<br/>");
}
}
runRepl("underscore.string.f/utils", "lodash.string", "underscore.string");
runRepl("underscore.string.f", "lodash.string", "underscore.string");
runRepl("underscore.string", "lodash.string", "underscore.string");
runRepl("underscore.string/utils", "lodash.string", "underscore.string");
Escaping is necessary to match a literal . inside moduleName and ($|/)(.+)? presumes there can be something after an end of string. Also, (.+)? (1 or more characters) is actually the same as .* which is shorter and easier to read.
I have some difficulties with javascript. I'm currently working out a pagination skipper.
function skip(s)
{
var url = window.location.toString();
if(location.href.match(/(\?|&)currentpage=x($|&|=)/))
{
url=url.replace('currentpage=x','currentpage='+s);
window.location=url;
}
else
{
var newUrl = url+"¤tpage="+s;
window.location=newUrl;
}
}
I would like x to match any integer, so the entire string will be replaced.
Thanks!
The regex you're looking is this:
/((\?|&)currentpage=)\d+/
It matches and captures ?|¤tpage=, and matches the number that follows, but does not capture them. You can then replace the entire match with a string of your choice:
var newUrl = location.href.replace(/([?&]currentpage=)\d+/, '$1'+s);
Assuming that s here is the value for currentpage you want to replace the x in your example with. I've replaced the (\?|&) with a character class: [?&]. It simply matches a single character that is either a ? or an &. In the replacement string I back-reference the matched group ([?&]currentpage=), using $1, and concatenate s to it. It's as simple as that. To redirect:
location.href = location.href.replace(
/([?&]currentpage=)\d+/,
'$1' + s
);
And you're home free. Try it out in your console, like so:
'http://www.example.com/page?param1=value1¤tpage=123¶m2=foobar'.replace(
/([?&]currentpage=)\d+/,
'$1124'//replaced + s with 124
);
//output:
//"http://www.example.com/page?param1=value1¤tpage=124¶m2=foobar"
You can use following code,
function addParameter(url, param, value) {
// Using a positive lookahead (?=\=) to find the
// given parameter, preceded by a ? or &, and followed
// by a = with a value after than (using a non-greedy selector)
// and then followed by a & or the end of the string
var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))', 'i'),
qstring = /\?.+$/;
// Check if the parameter exists
if (val.test(url)) {
// if it does, replace it, using the captured group
// to determine & or ? at the beginning
return url.replace(val, '$1' + param + '=' + value);
}
else if (qstring.test(url)) {
// otherwise, if there is a query string at all
// add the param to the end of it
return url + '&' + param + '=' + value;
}
else {
// if there's no query string, add one
return url + '?' + param + '=' + value;
}
}
Usage,
function skip(s) {
window.location = addParameter(location.href, "currentpage", s);
}
Demo
I'm trying to write a function that will remove a query argument from a url in javascript. I think I have it using regex, but I'm not sure if I've missed anything. Also, I can't shake the feeling that there was probably a better way to do this that didn't involve me messing around with regex half the day and running the risk of later finding out that I didn't take some kind of corner case into account.
remove_query_argument = function(url, arg){
var query_arg_regex;
// Remove occurences that come after '&' symbols and not the first one after the '?'
query_arg_regex = new RegExp('&' + arg + '=[^(?:&|$)]*', 'ig');
url = url.replace(query_arg_regex, '');
// remove the instance that the argument to remove is the first one
query_arg_regex = new RegExp('[?]' + arg + '[^(?:&|$)]*(&?)', 'i');
url = url.replace(query_arg_regex, function (match, capture) {
if( capture != '&' ){
return '';
}else{
return '?'
}
});
return url;
}
Does anyone see any problems with this code or would like to suggest a better implementation or way of going about this?
Thanks!
If you have a lot of URL-related operations, you better try this awesome js library https://github.com/medialize/URI.js
Given a percent-encoded URL, the following function will remove field-value pairs from its query string:
var removeQueryFields = function (url) {
var fields = [].slice.call(arguments, 1).join('|'),
parts = url.split( new RegExp('[&?](' + fields + ')=[^&]*') ),
length = parts.length - 1;
return parts[0] + '?' + (length ? parts[length].slice(1) : '');
}
Some examples:
var string = 'http://server/path/program?f1=v1&f2=v2';
removeQueryFields( string, 'f1' ); // 'http://server/path/program?f2=v2'
removeQueryFields( string, 'f2' ); // 'http://server/path/program?f1=v1'
removeQueryFields( string, 'f1', 'f2' ); // 'http://server/path/program'