1

My input is many lines of text that looks like this:

a.b.c.d.e (f:g)

I need to turn this into

a.b.c.d.e (a/b/c/d/e/f?g)

Note that the dotted part (a.b.c.d.e) can have varying numbers of elements, so sometimes it'll be q.r.s.t, sometimes u.v.w.x.y.z and so on. I have a replace() that will give me (a.b.c.d.e.f?g), but what I need is then to turn all those .s into /s in the result.

Is there a way to do a replace inside a replace? Or should I just call replace() on the string twice?

Sorry if this question is poorly worded, I'm not awfully well versed at regular expressions in javascript.

3 Answers 3

4

A very crazy way of doing it:

var str = "a.b.c.d.e (f:g)";
var re = /([^\s]+)\s\(([^:]+):([^\)]+)\)/;
var newStr = str.replace(re, function(a,b,c,d){ return b + " (" + b.replace(/\./g,"/") + "/" + c + "?" + d + ")"; });

jsfiddle

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

1 Comment

replace() can take a function as its second parameter? that is so cool it hurts
3

You need to chain the calls to replace() one after the other.

var result = source.replace("foo", "bar").replace("oof", "rab");

Comments

1

A saner way :) http://jsfiddle.net/smfPU/

input = "a.b.c.d.e.w.x.y.z (f:g:h)";
output = input.replace(/:/g, "?");
outputparts = output.split("(");
left = outputparts[0];
middle = left.replace(/\./g, "/").trim();
right = outputparts[1];
output = left + "(" + middle + "/" + right;
document.write(output);

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.