1

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

asked Jun 12, 2010 at 11:58

3 Answers 3

4

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]);
answered Jun 12, 2010 at 12:01
Sign up to request clarification or add additional context in comments.

7 Comments

This doesn't have the OPs expected output "/but-keep-this", try not to use .split() for what .substring() was made for :)
@Nick Craver: It does: 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 - `"/but-keep-this" != "but-keep-this"``, my point is you're missing the slash :)
Ever better than I was expecting +1
@Nick Craver: hmm got your point, but now it is accepted one, can't do anything about it, however updated for that slash.
|
3
var s = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
pos = s.lastIndexOf("/");
var s2 = s.substring(pos);
alert(s2);
answered Jun 12, 2010 at 12:01

Comments

2

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.

answered Jun 12, 2010 at 12:00

2 Comments

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.