Hello struggling here guys..
Is it possible to string replace anything between the the first forward slashes with "" but keep the rest?
e.g. var would be
string "/anything-here-this-needs-to-be-replaced123/but-keep-this";
would end up like this
string "/but-keep-this";
Hope that made sence
3 Answers 3
You can simply split it by /
var str = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
var myarray = str.split('/');
alert('/' . myarray[2]);
7 Comments
"/but-keep-this", try not to use .split() for what .substring() was made for :)substring might be the way to go. OP might consider those with that answer if this doesn't do the trick for what he is trying to do.var s = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
pos = s.lastIndexOf("/");
var s2 = s.substring(pos);
alert(s2);
Comments
Like this:
var string = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
string = string.substring(string.indexOf('/', 1));
You can view a demo here to play with, the .indexOf() method takes an optional second argument, saying where to start the search, just use that with .substring() here.
If you want to remove all leading slashes (unclear from the example), change it up a bit to .lastIndexOf() without a start argument, like this:
var string = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
string = string.substring(string.lastIndexOf('/'));
You can play with that here, the effect is the same for the example, but would be different in the case of more slashes.
2 Comments
lastIndexOf to be sure to get only the last slash (I assume he's parsing paths)