0

I have the following function:

function replace(path) {
    return path.replace(/\//g, '.').replace(/^\./, '');
};

Can you please explain what exactly is doing? I have some hard time understanding it mostly because of the slashes and escapes.

I know it replaces something with something. :)

1
  • 1
    if you have trouble with Regex, this Website is very usefull for learing the basics: regexr.com Commented May 10, 2015 at 6:58

3 Answers 3

3
return path.replace(/\//g, '.').replace(/^\./, '');

The / at the start and end are delimiters of regex.

The \ inside it will escape the following character(\ and .).

  1. /\//g: Will find all(g: global flag) the / in the string and will replace it by .
  2. /^\./: Will find the . at the start(^) of the string and will remove it
Sign up to request clarification or add additional context in comments.

Comments

0

Replace / with ., and then replace . at the beginning of string with an empty string.

Comments

0

Let's assume that path is a string. strings in javascript, like everything else, are objects. Among other things, they have a replace function. You can read about it here.

Those things with the slashes are called regular expressions, or RegExs for short. You can read about them here and here. They are very useful and often used for manipulating strings with operations like replace.

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.