Dejan.S Dejan.S - 4 months ago 8
Javascript Question

Remove everything after a certain character

Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

like /Controller/Action?id=11112&value=4444


I want the href to be
/Controller/Action
only, so I want to remove everything after the "?".

I'm using this now:

$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
alert(url);

Answer
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);

Sample here

Edit:

I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).

2nd Edit:

Updated code to account for no '?':

var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);

http://jsfiddle.net/L4hna/1/