JavaScript: Concatenation
Often, strings need to be assembled from several parts, for example, to combine a first and last name, add a unit of measurement, or compose text from a template. The concatenation operation, that is, gluing strings together, is used for this.
How to combine strings
In JavaScript, strings are combined using the + operator. Even though this operator is also used to add numbers, in the case of strings it means combining, that is, gluing the contents together.
console.log('Dragon' + 'stone');
// => DragonstoneOrder matters. First comes the left part ('Dragon'), then the right part ('stone'). The result comes out in the order in which the operands are specified.
Here is how combining several strings works:
'Hello' + ', ' + 'World!'
└──┬──┘ └┬┘ └──┬───┘
└────┬───┘ │
'Hello, ' + 'World!'
└──────┬───────┘
'Hello, World!'Examples.
console.log('Kings' + 'wood'); // => Kingswood
console.log('Kings' + 'road'); // => Kingsroad
// Here we use double quotes on the outside because there is a single quote inside
console.log("King's" + 'Landing'); // => King'sLandingJavaScript lets you combine strings even if they are written with different quotes. The main thing is that both parts are strings.
A space is also a character
When combining, JavaScript does not insert spaces automatically. If there should be a space between the parts, it must be specified manually.
// Space at the end of the first string
console.log("King's " + 'Landing'); // => King's Landing
// Space at the beginning of the second string
console.log("King's" + ' Landing'); // => King's LandingThe result will be the same. But if you do not add a space, the words will glue together.
Escape sequences
In strings, you can use escape sequences, for example \n for a line break or \t for a tab. During concatenation, they work the same as any other characters.
console.log('Hello,' + '\n' + 'World!');
// Hello,
// World!In the same way, you can use the tab \t to align output.
console.log('A' + '\t' + 'B'); // => A BConclusion
Concatenation is the combining of strings via +, and strings can be combined regardless of the type of quotes.
- Gluing happens strictly in order from left to right.
- Spaces are not added automatically; they must be included in the strings manually.
Instructions
The site automatically generates links to repository pages by assembling them from separate parts. Assemble the link using concatenation and print it to the screen:
https://github.com/hexlet/exercises-javascriptEach URL component is a separate string: the protocol, the domain, the owner name, and the repository name.
Tips
If the editor contains
// BEGINand// END, then the code must be written between these lines.
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('hello world', async () => {
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe('https://github.com/hexlet/exercises-javascript');
});Teacher's solution will be available in:
20:00
