views:

137

answers:

5

Hi,

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.

A: 

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).

Shawn Steward
+1  A: 

Yes it will. And also note that you don't have to use regular expressions in .replace(), .replace('tab_', ''); will do just fine.

Tatu Ulmanen
You don't even have to use replace if you know that you always want to remove the first `k` chars of the string, cf. my answer.
Jørn Schou-Rode
+1  A: 

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.

Jørn Schou-Rode
+2  A: 

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?

nes1983
I don't think the OP wants to do any kind of source code rewriting, but the title of the question sure makes it sound that way.
Jørn Schou-Rode
That did spring to my head, however I need both variables, as tab_something, shows up a relevant div element, while something highlights it on the nav. (and yes, it should probably be the other way round)
daulex
+2  A: 

A couple of things:

  • document.location will be deprecated at some point by document.URL, consider using window.location.
  • Consider also using 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.

CMS
Thank you very much for the tips.
daulex