Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);  } 
like image 562
Dejan.S Avatar asked Apr 12 '11 06:04

Dejan.S


People also ask

How do I delete everything after a character in Notepad ++?

If you want to delete all the text after a character or string (to the right) in Notepad++ you would need to make use of regex. So, simply add . * to delete all characters after the string or character on each that you want to delete from a line.

How do you delete everything after a character in python?

To remove everything after the first occurrence of the character '-' in a string, pass the character '-' as separator and 1 as the max split value. The split('-', 1) function will split the string into 2 parts, Part 1 should contain all characters before the first occurrence of character '-'.


2 Answers

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

like image 116
Demian Brecht Avatar answered Oct 30 '22 11:10

Demian Brecht


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

url.split('?')[0] 

jsFiddle Demo

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

like image 45
kapa Avatar answered Oct 30 '22 10:10

kapa