Hello I'm new to javascript and I need a little help with regex/replace
I want to take a url for example (url case 1)
http://url.com/_t_lastUpdate_2670619?location=50457347
or (url case 2)
http://url.com/_t_2670619
I want to select in this case just
_t_2680619
Ignore everything after "?" and before (underscore)t(underscore)
Is it possible with regex/replace? the only thing I managed to do was select numbers only with
var _t__and_number = document.URL.replace(/[^\d]/g, '');
alert(_t__and_number);
But that doesn't solve my problem if there's something like url case 1
(if I could get just the first number even without the (underscore)t(underscore) it would already help me a lot.
Thanks
Solutions:
onetrickpony/michaelb958:
var _t__and_number = window.location.pathname;
alert(_t__and_number);
ermagana:
var _t__and_number = document.URL.replace(/\?.*/g, '').match(/.*\/(.*)/)[1];
alert(_t__and_number);
As suggested by onetrickpony, if this is the URL you are currently browsing, window.location.pathname will yield that part of the URL.
First Part like case (1) and (2)
var s = '//url.com/_t_522121?location=50457347';
var n = s.lastIndexOf('/');
var result = s.substring(n + 1);
alert(result);
n = result.indexOf('?');
result = result.substring(0, n);
alert(result);
If you're trying to pull out the value after the last / and before the ? you could try something like this
url.replace(/\?.*/g, '').match(/.*\/.*(_t_.*)/)[1]
The replace removes everything from the ? and forward, the match creates a group of the values found after the last forward slash which is then accessed by the index 1
Hope this helps.
here is the jsfiddle to show it works:
My JsFiddle
Related
This should be pretty easy but I'm struggling.
I have a button that fires a function. I want an alert to fire as well that tells me which page the user was on.
www.whatever.com/thispage1/whatever
www.whatever.com/thispage2/whatever
www.whatever.com/thispage3/whatever
So after my button is clicked, I want an alert that reads back "thispage1" or "thispage2" etc. I do not want the entire URL fed back to me. Is there a way to find text in a url based on its position or number of characters before it starts?
Look at window.location.pathname and use str.slice to extract the bit you want, with str.indexOf to find the indices to start/end at
var top_dir = window.location.pathname.slice(
1,
window.location.pathname.indexOf('/', 1)
);
Maybe this will help you get started. Key players here are window.location.pathname and string.split()
var returnPage = function() {
var urlString = window.location.pathname;
var stringArray = urlString.split("/");
return stringArray[0]; // number == whichever piece of the array you want to get
};
function myFunction() {
alert(returnPage());
}
Title says it all. Basically I am looking to retrieve the end of the url using jQuery to add one to the selection and go to that page. I had some help from someone else on her but I want to understand how it is working/ why it's not working:
var urlFrags = window.location.href.replace(".html", "").split("_"),
curPage = parseInt(urlFrags[urlFrags.length]),
nextPage = "example_" + (curPage + 1) + ".html";
It could be an error somewhere else, but I am working down the line trying to bug-fix it.
I understand pretty much everything going on, except I don't understand parseInt() and stuff.
Would it be possible to '.getAsIntiger(urlFrags)' ? (I have tried this but I may have implemented wrong.)
The error there is here:
curPage = parseInt(urlFrags[urlFrags.length]);
You should be doing
curPage = parseInt(urlFrags[urlFrags.length-1]);
Since if you have a length of 2 in your array, you cannot access Array[2] because it doesn't exist. You have to access Array[1] because the array index starts in 0.
Why not do a var num = parseInt(/.+?_(\d+)\.html/.exec(window.location.href)[1])
What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();
For example I have a url like:
ftp://xxx:xxx#ftp.example.com/BigFile.zip
How can I get example.com from this url using javascript/jquery?
You can get the browser to parse the URL for you like this :
var a = document.createElement('a');
a.href = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip';
var host = a.hostname;
That gets you the hostname, which in this case would be ftp.example.com, if for some reason you have to remove the subdomain, you can do
var domain = host.split('.');
domain.shift();
var domain = domain.join('.');
FIDDLE
Here's the different parts to a URL -> https://developer.mozilla.org/en-US/docs/Web/API/Location#wikiArticle
Here is using javascript RegExp
input = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/);
match = pattern.exec(input);
alert(match[1]);
You can also use i at the end of regex to make it case insensitive.
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/i);
You can use jquery like this:
var url = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
var ahref = $('<a>', { href:url } )[0]; // create an <a> element
var host = ahref.hostname.split('.').slice(1).join('.'); // example.com
You can have a regex to do this for you.
url = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip'
base_address = url.match(/#.*\//)[0];
base_address = base_address.substring(1, base_address.length-1)
This would contain ftp.example.com though. You can fine tune it as per your need.
I just wanted to try/add something different (can't bet for performance or the general solution, but it works and hey ! without DOM/regexp involved):
var x="ftp://xxx:xxx#ftp.example.com/BigFile.zip"
console.log((x.split(".")[1]+ "." + x.split(".")[2]).split("/")[0]);
For the given case can be shortest since always will be ".com"
console.log(x.split(".")[1]+ ".com");
Another (messy) approach (and will work with .com.something:
console.log(x.substring((x.indexOf("#ftp"))+5,x.indexOf(x.split("/")[3])-1));
And well on this we're dependend about having "#ftp" and the slashes "/" (at least 3 of them or one after the .com.something) for example would not work with: ftp://xxx:xxx#ftp.example.com
Last update This will be my best
without DOM/RegExp, nicer (but also confusing) that the previous ones
solves the problem about having or don't the slashes,
still dependant on having "#ftp." in the string.
works with .com.something.whatever
(function (splittedString){
//this is a bit nicer, no regExp, no DOM, avoid abuse of "split"
//method over and over the same string
//check if we have a "/"
if(splittedString.indexOf("/")>=0){
//split one more time only to get what we want.
return (console.log(splittedString.split("/")[0]));
}
else{
return (console.log(splittedString));//else we have what we want
}
})(x.split("#ftp.")[1]);
As always it depends how maintainable you want your code to be, I just wanted to honor the affirmation about there's more than one way to code something. My answer for sure is not the best, but based on it you could improve your question.
Okay, so I have some variables in javascript...
var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;
As you can see, I have a link and a position. Using the position var I would like to replace some text in the link field. I would like to strip &pos2=1.teamsp00ky.chat from the link. Naturally, I have to do some basic regular expressions; the problem comes into when I try to use the position var in the regex. I just can't figure it out.
In PHP I could do the following:
preg_replace('/&pos'.$position.'=[^&]*/i', '', $link);
I tried the following in JS, but its not working:
link.replace(new RegExp('&pos'+position+'=[^&]*'), '');
Could someone help me out and tell me what I'm doing wrong? Also, how would I make it case-insensitive?
You need to set the value, not just call the method:
link = link.replace(new RegExp('&pos'+position+'=[^&]*'), '');
To make it case insensitive, use this regex:
new RegExp('&pos'+position+'=[^&]*', "i")
Although it might make it easier if you split the string on the "?", then split up the key/value pairs by "&", and then split them by "=".
Could someone help me out and tell me what I'm doing wrong?
replace does not mutate the string, but returns a new one - you'd have to assign it somewhere.
Also, how would I make it case-insensitive?
Pass the i flag to the RegExp constructor.
link = link.replace(new RegExp('&pos'+position+'=[^&]*', 'i'), '');
<div id="result"></div>
var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;
var start = link.indexOf("pos2");
var end = link.indexOf("&", start);
document.getElementById("result").textContent = link.slice(0, start) + link.slice(end + 1);
on jsfiddle