I have string delimited with dashes like:
x#-ls-foobar-takemeoff-
How can I remove takemeoff-
using javascript where takemeoff-
can be any amount of characters ending in a dash?
I have string delimited with dashes like:
x#-ls-foobar-takemeoff-
How can I remove takemeoff-
using javascript where takemeoff-
can be any amount of characters ending in a dash?
3 Answers
Reset to default 8var str = "x#-ls-foobar-takemeoff-";
var newStr = str.replace(/[^-]+-$/,"");
Basic regular expression says
[^-]+ <-- Match any characters that is not a dash
- <-- Match a dash character
$ <-- Match the end of a string
If you have a string str
, you can do the following:
str = str.substr(0, str.lastIndexOf("-", str.length - 2));
Using substr()
and lastIndexOf()
:
var myStr = "x#-ls-foobar-takemeoff-";
myStr = myStr.substr(0, myStr.length-1); // remove the trailing -
var lastDash = myStr.lastIndexOf('-'); // find the last -
myStr = myStr.substr(0, lastDash);
alert(myStr);
Outputs:
x#-ls-foobar
jsFiddle here.