2

Change

12-16-23-some-words-now

to

12/16/23/some-words-now

thanks!! Your help is much appreciated.

5 Answers 5

3

If the characters between the first three dashes are always numbers, you can do it like this:

variable = variable.replace(/^(\d+)-(\d+)-(\d+)-/, "$1/$2/$3/");

If they could be any arbitrary characters, then you can do it like this:

variable = variable.replace(/^([^-]+)-([^-]+)-([^-]+)-/, "$1/$2/$3/");

Working demo: http://jsfiddle.net/jfriend00/YySFh/

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

Comments

2
foo = foo.replace(/^(.*?)-(.*?)-(.*?)-(.*)$/, "$1/$2/$3/$4");

JSFiddle.

Comments

2

This should do the trick:

'12-16-23-some-words-now'.replace(/^(\d+)-(\d+)-(\d+)-/g, '$1/$2/$3/');

Are the first three always numbers?

3 Comments

Ah, @jfriend00 edited his answer just as I was answering. His won't necessarily replace the first three though, as he is missing the ^ operator.
yep. I'm generating these strings for one purpose where they cannot have backslashes, then use them to direct to a page, which requires the date (first three numbers) to be within backslashes.
+1 for noticing that it's actually three dashes that should be replaced, -1 for not noticing that there is no digit following the third dash :)
1

Find:

^([^-]*)-([^-]*)-([^-]*)-(.*)

Replace:

$1/$2/$3/$4

1 Comment

This one gets my vote. ([^-]* is more precise and faster than .*?). Say what you mean - mean what you say! +1
0

This exact structure can be fixed like this:

var string = "12-16-23-some-words-now";
var hyphensFormatted = string.substr(0, 9).replace(/-/g, "/");
var formattedString = hyphensFormatted + string.substr(9, string.length);
console.log(formattedString);

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.