Tuesday, May 4, 2021

Javascript Practice 26: JS Hero - String: replace()

 
Question: 

Write a function normalize, that replaces '-' with '/' in a date string.

Example: normalize('20-05-2017') should return '20/05/2017'.





Answer: 

function normalize (datestring) {

let a = datestring.replace ('-', '/');
let b = a.replace ('-', '/'); 

return b;
 
};

> we declare a variable 'a' 
> we initialize it with the value we get by using the replace() method
> we replace the '-' with '/'
> only the first occurence of '-' is replaced with '/' 
> we then declare another variable 'b'
> we initialize it with the value we get by using the replace() method on variable 'a' which has the updated datestring
> this time the second occurence of '-' on the datestring is replaced with '/' 
> we return the variable b to get our answer

No comments:

Post a Comment