0

I am looking for a regex pattern (and have been unable to come up with one) that can parse window.location.pathname and return the number of /s in it.

I am trying to keep all my path's relative to the home directory of my website.

For example: index.html has a script tag with an src="js/scripts.js". But that doesn't work if I access /episode/10/index.html. The path js/scripts.js is no longer valid. So my method is to write a simple javascript find and replace and return the number of /s in window.location.pathname. Subtract that number by 1 and change all the src to something like ../../

Any one know of a good quick easy way to do this?

4

3 回答 3

3

You can use this function I created:

String.prototype.count = function(a) {
    return this.match(new RegExp(a, "g")).length;
};
alert("Hi/how/are/you".count("/"))​;  // Alerts 3

jsFiddle Example

Just attach the window.location.pathname to this function:

window.location.pathname.count("/");
于 2012-07-27T01:27:10.580 回答
3

How about just splitting on '/' and counting the number of array elements produced?

var slashCount = window.location.pathname.split('/').length - 1;

I can't shake the feeling that this is solving the wrong problem, though...

于 2012-07-27T01:31:31.393 回答
0

The appropriate method is String.prototype.match:

var slashCount = s.match(/\//g).length;
于 2012-07-27T02:17:02.227 回答