Remove everything after a certain character

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

Solutions/Answers:

Solution 1:

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/

Solution 2:

You can also use the split() function. This seems to be the easiest one that comes to my mind :).

url.split('?')[0]

jsFiddle Demo

Related:  How do I toggle an ng-show in AngularJS based on a boolean?

One advantage is this method will work even if there is no ? in the string – it will return the whole string.

Solution 3:

var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action

This will work if it finds a ‘?’ and if it doesn’t

Solution 4:

If you also want to keep “?” and just remove everything after that particular character, you can do:

var str = "/Controller/Action?id=11112&value=4444",
    stripped = str.substring(0, str.indexOf('?') + '?'.length);

// output: /Controller/Action?

Solution 5:

Worked for me:

      var first = regexLabelOut.replace(/,.*/g, "");

Solution 6:

May be very late party :p

You can use a back reference $’

$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"

let output = str.replace(/\?.+/g,"$'")

console.log(output)