Javascript – Remove everything after a certain character

javascriptjquery

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 this

/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');

     console.log(url);
 }

Best Answer

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

Sample here

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

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

Sample here