string - How to find the last given character in JavaScript? -


for example, there string "apple red; banana yellow; orange orange;dummytest"

i'd find last ";" , rid of after character. like:

"apple red; banana yellow; orange orange"

i know ordinary ways what's easiest way?

easiest way can think of use combination of substring , lastindexof so:

var s = "apple red; banana yellow; orange orange;dummytest"; s = s.substring(0, s.lastindexof(";")); //s = "apple red; banana yellow; orange orange" 

here working example


normally, 1 might inclined validate input string first. so:

var isvalid = s.lastindexof(";") > -1; 

however, javascript wont throw error if use substring -1 length parameter (unlike c# example), end empty string result 1 want anyway.


also, completeness, cut string @ first occurrence of character using indexof function, so:

s = s.substring(0, s.indexof(";")); //s = "apple red" 

Comments