Hi!
I have a string "foo_bar" and "foo_foo_bar". How do I remove the last "_bar" from the string? So I'm left with "foo" and "foo_foo".
Thanks
Hi!
I have a string "foo_bar" and "foo_foo_bar". How do I remove the last "_bar" from the string? So I'm left with "foo" and "foo_foo".
Thanks
use subString to get everything to the left of _bar. But first you have to get the instr of _bar in the string.
str.substring(3,7);
3 is that start and 7 is the length
You can use the substring method of Javascript string objects:
s = s.substring(0, s.length - 4)
unconditionally removes the last 4 characters from string s
.
If you want to conditionally remove the last 4 characters only of they are exactly _bar
:
var re = /_bar$/;
s.replace(re, "");
if(str.substring(str.length - 4) == "_bar")
{
str = str.substring(0, str.length - 4);
}
Regular expression is what you are looking for.
var str = "foo_bar";
alert(str.replace(/_bar$/, ""));
The easiest method is to use the slice
method of the string, which allows negative positions (corresponding to offsets from the end of the string):
var withoutLastFourChars = s.slice(0, -4);
If you needed something more general to remove everything after the last underscore, you could do the following (so long as s
is guaranteed to contain at least one underscore):
var withoutLastChunk = s.slice(0, s.lastIndexOf("_"));