[javascript] 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);
 }

This question is related to javascript jquery

The answer is


It can easly be done using JavaScript for reference see link JS String

EDIT it can easly done as. ;)

var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

It works for me very nicely:

var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result =  x.substring(0, remove_after);
alert(result);

Worked for me:

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

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


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


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?

May be very late party :p

You can use a back reference $'

$' - Inserts the portion of the string that follows the matched substring.

_x000D_
_x000D_
let str = "/Controller/Action?id=11112&value=4444"_x000D_
_x000D_
let output = str.replace(/\?.+/g,"$'")_x000D_
_x000D_
console.log(output)
_x000D_
_x000D_
_x000D_