I hava a url like
mysite.net/home/index/page/XX
while XX is any number. I need to replace XX and remove everything that might be behind XX. So I would like to remove everything behind page/ by replacing it with a number.
There are a lot of methods for string manipulation http://www.w3schools.com/jsref/jsref_obj_string.asp
I know how to perform this but I am not sure which methods to use. So I ended with getting the lastIndexOf("page/"). So this +1 would give me the starting point for replacing the string. The entire length of the string would be the ending point.
Any ideas?
The following code will do the trick, by using regular expression:
"mysite.net/home/index/page/XX".replace(/\/page\/.*/, '/page/123')
var url = "mysite.net/home/index/page/XX"
return url.substr(-(url.length - (url.lastIndexOf("page/") + 5))))
I don't get your problem because you may have found everything you need...
var yourURI = "mysite.net/home/index/page/XX";
var theDelimiter = "page/";
var yourNewIndex = "42";
var yourNewURI = null;
var lastIndexOfDelimiter = yourURI.lastIndexOf(theDelimiter);
if (lastIndexOfDelimiter != -1)
{
yourNewURI = yourURI.substr(0, lastIndexOfDelimiter + theDelimiter.length) + yourNewIndex;
}
Is that what you want?
This isn't a direct answer to your question, but the way I solve this kind of problem is to have the server calculate a 'base url' (mysite.net/home/index/page/ in your case), and write it to a js variable at the time the page is built.
For two different ASP.NET MVC versions (there would be something similar you could do in any other framework) this looks like this:
var baseUrl = '#ViewBag.BaseUrl';
or
var baseUrl = '<%: ViewData["BaseUrl"] %>';
This has the big advantage that the page JS doesn't start to know about URL formation, so if you change your URL routing you don't find little breakages all over the place.
At least for ASP.NET MVC, you can use the frameworks routing API to generate the base URL at the server side.
Related
I have a website like below:
localhost:3000/D129/1
D129 is a document name which changes and 1 is section within a document.
Those two values change depends on what user selects.
How do I just extract D129 part from the URL using javascript?
window.location.pathname.match(/\/([a-zA-Z\d]*)/)[1]
^ that should get you the 1st string after the slash
var path = "localhost:3000/D129/1";
alert(path.match(/\/([a-zA-Z\d]*)/)[1])
You can use .split() and [1]:
a = "localhost:3000/D129/1";
a = a.split("/");
alert(a[1]);
This works if your URLs always have the same format. Better to use RegEx. Wanted to answer in simple code. And if you have it with http:// or something, then:
a = "http://localhost:3000/D129/1";
a = a.split("/");
alert(a[3]);
ps: For the RegEx version, see Tuvia's answer.
I want to get the my exact location (only PHP page) using javascript, I'm currently using window.location to get the exact url for example: localhost/empc/myfolder/functions.php what is the code if I want to get only functions.php as a result? Is it possible? Thank you.
You can use location object to do this, To remove the "/" before the file name you can use substring method.
location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
you can try this pretty simple
var url = 'localhost/empc/myfolder/functions.php';
var url = url.split('/');
alert(url.pop());
It is possible. Use the javascript split function to separate the string into pieces and then access the last element to get the file name:
var str = "localhost/empc/myfolder/functions.php";
var arr = str.split("/");
alert(arr[arr.length-1]); //this will alert functions.php
I'm trying to convert html to bbcode.
My code:
var html = "<font color=\"Green\"><font size=\"4\">test</font></font>"
html = html.replace(/\<font color="(.*?)"\>(.*?)\<\/font\>/ig, "[color=$1]$2[/color]");
Result:
[color=Green]<font size="4">test[/color]</font>
But I need to get another
[color=Green]<font size="4">test</font>[/color]
Please could you correct my mistake. Sorry for my English.
You're going to have difficulty parsing html with regex as you can see from the many many posts on this site about it. Html is not a regular language, and it therefore can be impossible to parse in this way. That being said, if the problem is this simple it should be possible.
Here's a solution that will work in very simple cases to get the first and last part
var html = "<font color=\"Green\"><font size=\"4\">test</font></font>"
,findTag = /<.*?>|([^<]+)/g
,part
,allParts = []
;
while((part = findTag.exec(html)) !== null) {
allParts.push(part[0]);
}
console.log(allParts)
var first = allParts[0]
,last = allParts.slice(-1)[0]
;
console.log(first, last);
You can then parse the first and last as you were doing previously and use array.join() to join everything back.
But again, this will only work in the simple case.
Use negative lookaheads:
html = html.replace(/\<font color="(.*?)"\>(.*?)\<\/font\>(?!\<\/font\>)/ig, "[color=$1]$2[/color]");
To explain what's happening here: The pattern I used is exactly yours, except for an appended (?!\<\/font\>). This so-called negative lookahead basically says: "only make this a match, if I don't encounter </font> next".
Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.
- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...
My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?
- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2
Here's the JS code I'm using (found online)
$(document).ready(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".html","");
if(truePath === "") {
$("body").attr("id","index");
}
else {
$("body").attr("id",truePath);
}
});
Thanks in advance!
edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.
http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.
Using the javascript split function might be of help here. For example (untested, but the general idea):
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
$('body').id = segments[0];
Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
for (var i = 0; i < segments.length; i++) {
$('body').addClass(segments[i]);
}
EDIT:
Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...
var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');
If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...
url = url.replace(/\?.+$/,'');
Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..
var $body = $('body');
for ( ... ) {
$body.addClass( ...
}
Your regex is only going to select the last part of the url.
var getLast = pathname.match(/./(.)$/)[1];
You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.
If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.
edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.
What are you actually trying to do?
Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.
$(document).ready(function() {
$("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}
You want to get the first part of the path instead of the last:
var getFirst = pathname.match(/^\/([^\/]*)/)[1];
If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:
var getLast = pathname.match(/\/(page\d+)\//)[1];
The above would match "page" followed by a number of digits (omitting the 'html' ending too).
I have one string
var str = '';
str += 'category='+jv('category')+'&';
str += 'refresh_rate='+jv('refreshRate')+'&';
str += 'submit=Y';
now I want to take values from jv('category') and jv('refreshRate') in separate string in javascript (I want to extract values after "=" and before "&").
Thanks.
I've used this: http://blog.stevenlevithan.com/archives/parseuri
URI Parser in the past and find it simple to use and it doesn't rely on any other libraries. Its also pretty lightweight.
The author has a demo page but doesn't really explain how to use it..
Its really simple, you just do something like this:
var url = "http://my-site.com:8081/index.html?query=go&page=2";
var parsed = parseUri(url);
From there you can get things like the host/protocol/port/etc..
When dealing with the querystring you do
var page = parsed.queryKey.page;
alert(page); //alerts 2
Click the parse button on the demo page to see all properties of the parsed URI object that you can access..
You can use http://github.com/allmarkedup/jQuery-URL-Parser or any other URL parser for this sort of string.