Find and replace a string with a number attached - javascript

Sample URL:
.com/projects.php?&filterDate=this_week?page=5
The query strings like I've listed above may or may not have the ?page=5 query string in them. I'm looking for a way to grab the URL (done), search the string to determine whether or not it has the ?page=# query string (also done), add it in if it's not there (also done), but if it is there, replace it with a different number (need help with this). The code currently doesn't change the query string (ie page=5 doesn't change to page=6 or anything else for that matter). It doesn't seem like the .replace method's regex is correct (see current_window_location3 variable) below.
//Get the current URL
var current_window_location = window.location.href;
if(current_window_location.match("\\?page=([^&]+)")){
//Replace this query string
var current_window_location3 = current_window_location.replace("\\?page=([^&]+)", new_page_num);
//Go to this newly replaced location
window.location = current_window_location3;
}else{
//Add clicked '?page=#' query string to the URL
var current_window_location2 = current_window_location + "?page="+new_page_num;
//Go to this new location
window.location = current_window_location2;
}

String.prototype.replace() takes as its first value, the search pattern, a string or a regex. If a string ("abc?") is given, it searches for the literal string to replace. If a regex (/abc?/) is passed a regex match, a search is done using regular expressions.
Change your
var current_window_location3 = current_window_location.replace("\\?page=([^&]+)", new_page_num);
to
var current_window_location3 = current_window_location.replace(/\?page=([^&]+)/, new_page_num);
Here's an illustrating snippet:
var current_window_location = '.com/projects.php?&filterDate=this_week*?page=5*',
window_location = '',
new_page_num = 123;
if(current_window_location.match("\\?page=([^&]+)")){
//Replace this query string
var current_window_location = current_window_location.replace(/\?page=([^&]+)/, new_page_num);
//Go to this newly replaced location
window_location = current_window_location;
} else {
//Add clicked '?page=#' query string to the URL
var current_window_location = current_window_location + "?page="+new_page_num;
//Go to this new location
window_location = current_window_location;
}
document.write("window_location = " + window_location);

Related

Compare and match last part of URL with and accented/unaccented input value

I want to match the last part of the site url with an input value. This string starts with #.
The input value can have accents or not.
This is what I have right now:
$(function () {
var loc = window.location.href.split("#")[0]; // returns the full URL
var href = location.href;
var hrefM = href.match(/#([^\/]*)\/*$/)[1];
var hreflocation = hrefM.replace(/-/g, " ").toProperCase();
if (hreflocation) {
$(".wpcf7-list-item :input[value= '" + hreflocation + "' ]").parent().addClass("active");
$(".wpcf7-list-item :input[value= '" + hreflocation + "' ]").attr("checked",true);
}
});
It works fine when there are no accents.
Do you know how to adjust my hrefM so that although this word has no accents it is the same as an input with accents?
For example, this comparison doesn't work right now:
url hreflocation = "#produccio"
<input value="producció">
But this comparison works well:
url hreflocation = "#produccio"
<input value="produccio">
First, I'd like to point out a few things.
The text after the # in the URL is called the hash, and you can access it with location.hash.
<String>.toProperCase is not a function.
You cannot match all possible latin diacritics and variations in an attribute selector.
You can instead do:
$(function() {
if (location.hash) {
const hash = location.hash.substring(1).replaceAll('-', ' ');
const matchedInput = $(".wpcf7-list-item input").toArray()
.find(input => input.value.normalize('NFKD').replace(/\p{Diacritic}/gu, '') == hash);
}
});
hash takes the location hash, removes the #, and converts all - to
$(".wpcf7-list-item input").toArray() selects all input elements inside the .wpcf7-list-item and converts them to an array (to allow you to process them with JavaScript)
.find looks for an element in the array whose value, when normalized and stripped of diacritics, is equal to hash
You can then use $(matchedInput) however you want. If you instead want an array of matched inputs, you can replace find with filter.

Replacing hash with a string in the first n-characters of a url hash

I have a $location.path() that is of the following type of format:
/request/add/c3smsVdMHpVvSrspy8Vwrr5Zh8qSyP7q
I am interested in filtering the hash after /request/add/ to the following. As you can see, the last four chars are shown, but everything else before that is labeled as [FILTERED]
/request/add/[FILTERED]yP7q
I did some basic code which converts the hidden chars to #, but I got stuck in trying to apply the string [FILTERED] after the /request/add.
old_path = $location.path()
path = old_path.replace(/.(?=.{4,}$)/g, '#');
You could use substring. This will give you the [FILTERED] contents then you can do whatever you'd like with them.
var old_path = '/request/add/c3smsVdMHpVvSrspy8Vwrr5Zh8qSyP7q';
var filtered = old_path.substring('/request/add/'.length, old_path.length - 4);
var path = old_path.replace(filtered, '[FILTERED]');
console.log(path);

How do I extract data from this URL using javascript?

I need to build a string from the data contained in this url using javascript/jQuery:
http://www.example.com/members/admin/projects/?projectid=41
The string returned should look as follows:
/ajax/projects.php?projectid=41
Obviously if there is no query string present, the method should still return a string of the same format minus the query string. e.g.
http://www.example.com/members/admin/messages/
should return...
/ajax/messages.php
I've made numerous attempts, all met without success due to my poor grasp of regular expressions, and it feels as though the ore I rad on the subject the more I am confusing myself.
If someone could help it would be greatly appreciated.
EDIT: The 'admin' portion of the url is a users 'username' and could be anything.
Here's a function that will take your URL and return a new one according to the rules you've listed above:
function processURL(url) {
var base = "", query = "";
var matches = url.match(/([^\/\?]+)(\/$|$|\?|\/\?)/);
if (matches) {
base = matches[1];
matches = url.match(/\?[^\?]+$/);
if (matches) {
query = matches[0];
}
}
return("/ajax/" + base + ".php" + query);
}
And, a test app that shows it working on a bunch of URLs: http://jsfiddle.net/jfriend00/UbDfn/
Input URLs:
var urls = [
"http://www.example.com/members/admin/projects/?projectid=41",
"http://www.example.com/members/bob/messages/",
"http://www.example.com/members/jill/projects/",
"http://www.example.com/members/alice/projects?testid=99",
"http://www.example.com/members/admin/projects/?testid=99"
];
Output results:
/ajax/projects.php?projectid=41
/ajax/messages.php
/ajax/projects.php
/ajax/projects.php?testid=99
/ajax/projects.php?testid=99
To explain, the first regular expression looks for:
a slash
followed by one or more characters that is not a slash and not a question mark
followed by one of the four sequences
/$ a slash at the end of the string
$ end of the string
? a question mark
/? a slash followed by a question mark
The point of this regex is to get the last segment of the path that comes before either the end of the string or the query parameters and it's tolerant of whether the last trailing slash is there or not and whether there are any query parameters.
I know exactly what you are trying to do. In order to do it your way just split your string on question mark and then use last item form your array.
var data = your_url.split('?');
var newUrl = '/ajax/projects.php' + (data.length > 1 ? data[length-1] : "");
and you will have your url.
But what you can do is execute same url using your Script just add one parameter IsAjax=true and then check it in codebehind and execute your ajax logic.
e.g.
$('#somelink').onclick(function(){
$.ajax({ url: $(this).href, data { IsAjax: true } .... }
});
Using this way you will have more robust app.
I'll assume that by
http://www.example.com/members/admin/messages/
should return...
/ajax/members.php
you meant - should return...
/ajax/messages.php
If that is the case try
var query = url.split('?');
var paths = query[0].split('/');
var path = paths.pop();
if (path == '') //when there is trailing slash
path = paths.pop();
if (query.length == 1) //no query string
newurl = '/ajax/' + path + '.php';
else //query string
newurl = '/ajax/' + path + '.php?' + query[1];
I'm sure it can be made simpler and better, but that might give you a start.
var str = "http://www.example.com/members/admin/projects/?projectid=41";
var newStr = "/ajax/" + str.split("/").slice(-2).join(".php");
console.log(newStr);

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/

JavaScript: How to Strip out everything and just get the ID?

I'm creating a Bookmarklet for YouTube, i want to get the ID from the youtube link,
Ex: http://www.youtube.com/watch?v=YgFyi74DVjc
I want only "YgFyi74DVjc" from the above link, that's just an example of what i want, it has to strip out everything and just leave that end part, another thing is
i want to get the ID from this URL as well
http://www.youtube.com/verify_age?next_url=http%3A//www.youtube.com/watch%3Fv%3D[YOUTUBEID]
So basically when you click on some video and then on this bookmarklet it gets the youtube video ID and redirects them to a link which unlocks the video or expands the video to full size of the user's browser, i have everything coded and just need a way to get ID's from both the links, i have coded this which works for the 2nd link
var url = "http://www.youtube.com/verify_age?next_url=http%3A//www.youtube.com/watch%3Fv%3D[YOUTUBEID]";
var ytcode = url.substr(80,50);
alert(ytcode);
Now i want someway to get ID's from both the links, please help!
This is a job for regex:
url.match(/(\?|&)v=([^&]+)/).pop()
which, broken down, means:
url.match(
// look for "v=", preceded by either a "?" or a "&",
// and get the rest of the string until you hit the
// end or an "&"
/(\?|&)v=([^&]+)/
)
// that gives you an array like ["?v=YgFyi74DVjc", "?", "YgFyi74DVjc"];
// take the last element
.pop()
You can use this for the second form as well if you decode it first:
url = decodeURIComponent(url);
The url variable now equals "http://www.youtube.com/verify_age?next_url=http://www.youtube.com/watch?v=[YOUTUBEID]", and the regex should work.
You could put it all together in a reusable function:
function getYouTubeID(url) {
return decodeURIComponent(url)
.match(/(\?|&)v=([^&]+)/)
.pop();
}
Assuming the ID (i.e. the v parameter) is always the last parameter in the URL:
url = url.replace("%3D", "=");
var splitUrl = url.split("=");
var yId = splitUrl[splitUrl.length - 1];
The replace function is used to replace the character code %3D with =, which is what it represents. You can then split the string on the = character, and your ID will be the last element in the resulting array.
You could use this function (just pass it the url and the name of the parameter)
function getParameterByName( name, url )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var url = "http://www.youtube.com/watch?v=YgFyi74DVjc"
var v= getParameterByName('v', url);
Slight modification to nrabinowitz answer to allow for YouTube share URLs such as:
http://youtu.be/3Ah8EwyeUho
Also i have attached it to a class so it can be easily reused.
$(function(){
$('.js-youtube').on('blur', function(){
var newval = '';
if (newval = $(this).val().match(/(\?|&)v=([^&#]+)/)) {
$(this).val(newval.pop());
} else if (newval = $(this).val().match(/(youtu\.be\/)+([^\/]+)/)) {
$(this).val(newval.pop());
}
});
});

Categories

Resources