12

I wonder how can i remove all string part after "#". For example if i have example.com/hello#item1 how can i remove all characteres after # and # character too?

6
  • you got 3 completely different ways to do it... take your pick Commented Aug 9, 2011 at 18:31
  • ...and none of them involve jQuery, of course. Commented Aug 9, 2011 at 18:32
  • Good to know. Just involve JavaScript? Commented Aug 9, 2011 at 18:34
  • @Cris, indeed. You don't need jQuery to manipulate strings unless you want to trim them, and even that can be done with a simple regex too. Commented Aug 9, 2011 at 18:37
  • Regex are the same in most of languages? Commented Aug 9, 2011 at 18:42

6 Answers 6

50
var string = "example.com/hello#item1".split('#')[0];

simple as that

Sign up to request clarification or add additional context in comments.

2 Comments

Note, that string will be undefined, when # is not found. You might think, that it should return the whole string in that case instead.
it will always return whole string.
4

You can just use split.

var oldString ='somestring#removethis';
var newString = oldString.split('#', 1)[0];
alert(newString);

see: http://jsfiddle.net/DGFuf/1/

Comments

3
var str = "example.com/hello#item1";
str = str.replace(/#.*$/,'');

2 Comments

maybe i do somethin wrong but this code cuts all except domain.
It should be if You saying that. My mistake somewhere for sure.
2

Try this:

var str = "example.com/hello#item1";

    var newStr = str.substring(0, (str.length - str.indexOf("#")));

1 Comment

is this the opposite of code golf? what would that be called..? code flog?
2

You can also use this:

var str = "example.com/hello#item1".split('#')[0];

Comments

1
location.href.replace(location.hash,"")

that'll do it

edit

oops... string... hm... well this is how you remove it from the url XDDD

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.