0

I have the following string

let string = "01,15,01,45"

Which i want to turn to this

string = "01:15 - 01:45"

but i'm only able to come up with

"01,15,01,45".replace(/,/g, ':') // Gives "01:15:01:45"

but then i'm not sure how to get the index of the 5th position in string and replace it to ' - '

Any suggestion will be helpful.

1
  • 1
    if the length is known, you can just do "01,15,01,45".replace(/(\d\d),(\d\d),(\d\d),(\d\d)/, "$1:$2 - $3:$4") Commented Jul 26, 2020 at 12:54

3 Answers 3

3

Don't try doing things in one step when it would be clearer as multiple steps.

let string = "01,15,01,45";
let parts = string.split(",");
let result = `${parts[0]}:${parts[1]} - ${parts[2]}:${parts[3]}`;
Sign up to request clarification or add additional context in comments.

1 Comment

When you get so fixated on solving your problamatic approach and you forget other simpler solutions. Thank you so much.
1
let string = "01,15,01,45";

stringArray=string.split(',');

firstInterval=stringArray.slice(0, stringArray.length/2);

Output: ["01", "15"]

secondInterval=stringArray.slice(stringArray.length/2,stringArray.length);

Output:["01", "45"]

firstIntervalString=firstInterval[0]+":"+firstInterval[1];

Output: "01:15"

secondIntervalString=secondInterval[0]+":"+secondInterval[1];

Output: "01:45"

completeInterval=firstIntervalString+" - "+secondIntervalString;

Output: "01:15 - 01:45"

I think the code is self-explanatory. Still, please feel free to let me know if any part is not clear.

Comments

1

Another approach with matching pairs and replacing leftover commas.

let string = "01,15,01,45",
    result = string.match(/\d\d,\d\d/g).map(p => p.replace(/\,/, ':')).join(' - ');

console.log(result);

1 Comment

Thanks @Nina Scholz

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.