Reputation: 1635
Say I have a variable
tab_something
I need to drop the tab_
bit.
In php it's easy, using str_replace
...
Will
tabSelect = document.location.hash.substr(1,document.location.hash.length);
(which would always be tab_something
)
document.write(tabSelect.replace(/tab_/i, ""));
Work the way I would like it to, consistently across all modern browsers (ie6+) ?
Cheers.
Upvotes: 2
Views: 319
Reputation: 38346
If document.location.hash
always contains tab_
+ some other string that you wish to retrieve, why not take advantage of the prefix always being the same length? You already have call substring()
so why not let this function cut of a few more chars?
window.location.hash.substring(5)
Thanks to CMS for pointing out that window.location
is preferred to document.location
.
Upvotes: 1
Reputation: 827724
A couple of things:
document.location
will be deprecated at some point by document.URL
, consider using window.location
.String.substring
, since it is part of the ECMA-262 Spec.var tabSelect = window.location.hash.substring(1); // remove "#"
tabSelect = tabSelect.replace(/tab_/i, ""); // remove "tab_"
It will work on old and modern browsers.
Upvotes: 2
Reputation: 15756
Abusing source code rewrite as a substitute for reflection is … possible. I hate to state the obvious, but: maybe take a step back and see if you can reshape the project a bit, such that you can come up with a cleaner solution?
Upvotes: 2
Reputation: 124828
Yes it will. And also note that you don't have to use regular expressions in .replace()
, .replace('tab_', '');
will do just fine.
Upvotes: 1
Reputation: 6825
Yes that is a standard JavaScript function that's been around long enough to cover all modern browsers ie6 and above. Should work just fine.
You could also use substring if you know it will always be the first 4 characters. tabSelect.substring(4)
will give you everything starting the first character after tab_
(it is 0-based).
Upvotes: 0