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
Related
This is my console.log:
str : +0-D : replace : Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
I have the following function:
function replaceAll_withMatching(str, find, rep, prodId) {
//console.log(str + " : " + find + " : " + rep + " : " + prodId);
var returnString = "";
if (find.toLowerCase() == str.toLowerCase()) {
returnString = rep;
} else {
escfind = "\\" + find ;
var regexp = new RegExp(escfind, "i");
var match = regexp.test(str);
if (match) {
var regAHREF = new RegExp("\\<a", "i");
var AHREFMatch = regAHREF.test(str);
if (AHREFMatch == false) {
str = str.replace(regexp, rep);
str = replaceProductAll(str, PRODUCT_PLACEHOLD, prodId);
} else {
var aTagText = $($.parseHTML(str)).filter('a').text();
if ((find !== aTagText) && (aTagText.indexOf(find) < 0)) {
console.log(regexp);
console.log("str : " + str + " : replace : " + str.replace(regexp, rep));
str = str.replace(regexp, rep);
}
}
}
//console.log(str);
returnString = str;
}
//returnString = replaceProductAll(returnString, PRODUCT_PLACEHOLD, prodId);
return returnString;
}
This function looks for a "<a>" tag, if it doesn't find one then it does the replace. If it does find one it has some conditions that if everything checks out it does another replace.
The string that I'm passing in has been already "parsed" on the +0:
+0-D
In the second pass I'm expecting it to find the "D" in the above string, and then do the following replacement:
D
But as you can see, after the 2nd replace it is jumbling the string and producing malformed HTML
Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
More Context:
I have a string that needs to have a replace done on it. This is existing code so I'm not in a position to rework the function.
The original string is: +0-D
This string gets passed into the function below multiple times looking for matches and then if it finds a match it will replace it with the value (also passed in as a parameter).
When the +0-D gets passed in the first time the +0 is matched and a replace is done: +0
Then the next time the string is passed in: +0-D. The function finds the D as a match and it looks like it attempts to do a replace. But it is on this pass that the string gets jumbled.
Ultimately what I'm expecting is this:
+0-D
This is what I'm currently getting after the 2nd attempt:
Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
Further Context:
The +0-D is one of many strings this function handles. Some are very simple (i.e. Just +0), others are much more complex.
Question:
Based on the above, what do I need to do to get the regex to not jumble the string?
The problem was in the escfind:
escfind = "\\" + find;
var regexp = new RegExp(escfind,"i");
var match = regexp.test(str);
The first thing I did was in the 2nd replace clause I created a new RegExp to not use the "\\" + find;
if((find !== aTagText) && (aTagText.indexOf(find) < 0)){
try{
var regexp2 = new RegExp(find,"i");
var match2 = regexp2.test(str);
console.log(str.replace(regexp2,rep));
}catch(err){
console.log(err);
}
}
Then my string began to return as expected, however, when I opened it up to all the variations I was getting the Unexpected quantifier error.
Then I found this question - which lead me to escape out my find:
Once I replaced my code with this:
escfind = find.replace(/([*+.?|\\\[\]{}()])/g, '\\$1');
Then I got the output as expected:
<a href='+0'>+0</a>-<a href='D'>D</a>
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 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.
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'
So I am wanting to replace GET variable values in a url and if the variable does not exist, then add it to the url.
EDIT: I am doing this to a elements href not the pages current location..
I am not good with javascript but I do know how to use jQuery quite well and the basics of javascript. I do know how to write regex but not how to use the javascript syntax of regex and what functions to use it with.
Here is what I have so far and it does have an error on line 3: See it on jsfiddle(or below): http://jsfiddle.net/MadLittleMods/C93mD/
function addParameter(url, param, value) {
var pattern = new RegExp(param + '=(.*?);', 'gi');
return url.replace(pattern, param + '=' + value + ';');
alert(url);
}
No need to use jQuery on this one. Regular Expressions and string functions are sufficient. See my commented code below:
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 + '=.*?(?=(&|$))'),
parts = url.toString().split('#'),
url = parts[0],
hash = parts[1]
qstring = /\?.+$/,
newURL = url;
// Check if the parameter exists
if (val.test(url))
{
// if it does, replace it, using the captured group
// to determine & or ? at the beginning
newURL = 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
newURL = url + '&' + param + '=' + value;
}
else
{
// if there's no query string, add one
newURL = url + '?' + param + '=' + value;
}
if (hash)
{
newURL += '#' + hash;
}
return newURL;
}
And here is the Fiddle
Update:
The code now handles the case where there is a hash on the URL.
Edit
Missed a case! The code now checks to see if there is a query string at all.
I would go with this small but complete library to handle urls in js:
https://github.com/Mikhus/jsurl
See Change URL parameters. It answers your question in a more general manner (changing any url parameter). There are solutions for both jQuery and regular js in the answers section.
It also looks like url.replace should be location.replace but I may be wrong (that statement's based on a quick google search for 'url.replace javascript').
<script type="text/javascript">
$(document).ready(function () {
$('input.letter').click(function () {
//0- prepare values
var qsTargeted = 'letter=' + this.value; //"letter=A";
var windowUrl = '';
var qskey = qsTargeted.split('=')[0];
var qsvalue = qsTargeted.split('=')[1];
//1- get row url
var originalURL = window.location.href;
//2- get query string part, and url
if (originalURL.split('?').length > 1) //qs is exists
{
windowUrl = originalURL.split('?')[0];
var qs = originalURL.split('?')[1];
//3- get list of query strings
var qsArray = qs.split('&');
var flag = false;
//4- try to find query string key
for (var i = 0; i < qsArray.length; i++) {
if (qsArray[i].split('=').length > 0) {
if (qskey == qsArray[i].split('=')[0]) {
//exists key
qsArray[i] = qskey + '=' + qsvalue;
flag = true;
break;
}
}
}
if (!flag)// //5- if exists modify,else add
{
qsArray.push(qsTargeted);
}
var finalQs = qsArray.join('&');
//6- prepare final url
window.location = windowUrl + '?' + finalQs;
}
else {
//6- prepare final url
//add query string
window.location = originalURL + '?' + qsTargeted;
}
})
});
</script>