views:

39

answers:

4
+1  Q: 

Javascript replace

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

+2  A: 

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.

Nick Craver
Better using `lastIndexOf` to be sure to get only the last slash (I assume he's parsing paths)
nico
@nico - I wasn't sure about this (ambiguous example)...I re-read the question and was already adding it when you commented :)
Nick Craver
+4  A: 

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]);
Sarfraz
This doesn't have the OPs expected output `"/but-keep-this"`, try not to use `.split()` for what `.substring()` was made for :)
Nick Craver
@Nick Craver: It does: http://jsbin.com/ifabe3. And you are right `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.
Sarfraz
@Sarfraz - `"/but-keep-this" != "but-keep-this"``, my point is you're missing the slash :)
Nick Craver
Ever better than I was expecting +1
Webby
@Nick Craver: hmm got your point, but now it is accepted one, can't do anything about it, however updated for that slash.
Sarfraz
@Webby: If you want to remove the slash with the `lastIndexOf`/`substring` method just add +1 at the result (e.g.: `pos = s.lastIndexOf("/") + 1;`)
nico
@Webby: If this answer does the trick for you, no problem but i think @Nick Craver/@nico have better solution for the kind of thing you are doing.
Sarfraz
+2  A: 
var s = "/anything-here-this-needs-to-be-replaced123/but-keep-this";

pos = s.lastIndexOf("/");

var s2 = s.substring(pos);

alert(s2);
nico
A: 

you can also use regular expressions in javascript: http://www.regular-expressions.info/javascriptexample.html

Stefan Ernst