Remove everything after a certain character

var s="https://stackoverflow.com/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

Leave a Comment