0

In Javascript, I have a string for a path that looks like:

/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4

The prefix may or may not be there for each level. I need to create a new string which eliminates the prefix on each folder level, something like:

/Level1/Level2/Level3/Level4

OK. I've done something like the following, but I think perhaps with regex it could be made more compact. How could I do that?

var aa = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4"

var bb = aa.split("/").filter(String);
var reconstructed = "";

for( var index in bb )
{
 var dirNames = bb[index].split(":");
 if(dirNames.length==1) reconstructed += "/" + dirNames[0];
 else if(dirNames.length==2) reconstructed += "/" + dirNames[1];
 }
1
  • Wow! You guys are amazingly fast. Commented Sep 21, 2011 at 17:56

4 Answers 4

4

You can use regex like this:

var str = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var out = str.replace(/\/[^:\/]+:/g, "/");
alert(out);

This matches:

/
followed by one or more characters that is not a : or a /
followed by a :
and replaces all that with a / effectively eliminating the xxx:

Demo here: http://jsfiddle.net/jfriend00/hbUkz/

Sign up to request clarification or add additional context in comments.

Comments

2

Like this:

var bb = aa.replace(/\/[a-z]+:/g, '/');

Change the [a-z] to include any characters that might appear in the prefix, or just use [^\/:].

Comments

2
var a = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var b = a.replace(/\/[^\/]*:/g, "/");

Comments

1
aa = aa.replace(/\/[^:\/]\:/g, "/");

This function will replace every occurence of "/xxx:" by "/" using a RE, where xxx: is a prefix.

Comments

Your Answer

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.