views:

72

answers:

5

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

A: 

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

griegs
+3  A: 

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, "");
Alex Martelli
`slice` is better here. `s.slice(0, -4)`
Tim Down
A: 
if(str.substring(str.length - 4) == "_bar")
{
    str = str.substring(0, str.length - 4);
}
Matthew Flaschen
+2  A: 

Regular expression is what you are looking for.

var str = "foo_bar";
alert(str.replace(/_bar$/, ""));
w35l3y
Your solution works, but Alex's answer is more comprehensive. So I'll accept his. Thanks!
Albert
Not really a good idea. There's no need for a regular expression and it will be massively slower than using the `slice` or `substring` methods of the string.
Tim Down
A: 

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("_"));
Tim Down