Luis Antonio Pestana Luis Antonio Pestana - 4 months ago 21
Javascript Question

Javascript URL with Template String

I would like to mount a URL string with Template String. I want to know if it is possible.

This is what I am doing:

let url = `http://example.com/
MY_SERVICE/
MY_CONTROLLER/
${MY_FIRST_PARAM}/
${MY_SECOND_PARAM}`;


This code will return a string with break lines.

My question is: Is this possible to to this without break lines? The purpose is to have a more readable code.

My real URL is a little bit bigger than this.

Answer

You can call replace on any white space character after the template string:

let MY_FIRST_PARAM = 'foo';
let MY_SECOND_PARAM = 'bar';

let url = `http://example.com/
  MY_SERVICE/
  MY_CONTROLLER/
  ${MY_FIRST_PARAM}/
  ${MY_SECOND_PARAM}`
  .replace(/\s/g, '');

console.log(url);