# Strings

Video may be blocked due to browser extensions. In the article you will find a solution to this problem.

### Important notes

#### Lexicographical order

A lexicographical order is the order of words based on the alphabetical order of their component letters. This is the order used in dictionaries, phone books, contact books, etc.

In JavaScript, you can compare strings with `>` and `<`, and the comparison will be made lexicographically.

``````'a' < 'c';      // true, because a comes before c in the alphabet
'h' < 'b';      // false

'ab' < 'az';    // true, because first letters are the same, so the next letters are compared — b comes before z

'8' > '6';      // true
'8' > '12';     // true, because comparison is letter by letter, and 8 after 1 in the alphabet
``````

Remember, `'8'` is not a number, it's a string.

#### Interpolation

In addition to single quotation marks `''` and double quotation marks `""`, modern JavaScript offers backticks:

````````
``````

With backticks, you can interpolate instead of concatenation. Check this out:

``````const name = "Alex;"
const a = 10;
const b = 12;
console.log(`His name was \${name} and his age was \${a + b}`);
``````

This will print out `His name was Alex; and his age was 22`. Within `\${}` you can embed any expression.

### Lesson notes

• String is a sequence of characters
• An empty string is also a string (a sequence of zero characters)
• Denoted by single or double qutation marks

Creating a string constant:

``````const str1 = "Hello";
const str2 = 'Hello';
``````

Possible to include a qutation mark of one type within a string surrounded with the other type:

``````const str1 = 'They call him "Harry", and he likes it';
const str2 = "They call him 'Harry', and he likes it";
``````

If the same quotation mark is used within the string, then it needs to be escaped with a backslash `\`:

``````const str1 = 'They call her \'Ann\', and she likes it';
const str2 = "They call her \"Ann\", and she likes it";
``````

If the string includes a backslash, it needs to be escaped with another backslash:

``````const str = "This is a backslash \\ here"
// This is a backslash \ here
``````

There are also escape sequences: special combinations that generate invisible things:

``````const str = "Tere is a tab \t and here \ncomes the new line!"

// Here is a tab    and here
// comes the new line!
``````

`\t` is a tab, `\n` is a new line. Learn more about escape notation.

#### String concatenation

Strings can be glued together. This is called concatenation, and it's done with a `+` symbol:

``````const name = "Alex;"
const age = 22;
console.log("His name is " + name + " and his age is " + age);

// His name is Alex and his age is 22
``````

#### Accessing individual characters

`str[i]` is an i-th character of `str` string, starting from 0. For example, `"hexlet"[0]` is `h` and `"hexlet"[2]` is `x`.

Here is a function that takes a string and returns a copy of that string with every other letter skipped. For example, "hexlet" becomes "hxe".

``````const skip = (str) => {
let i = 0;
let result = '';

while (i < str.length) {
result = result + str[i];
i = i + 2;
}

return result;
}
``````

`str.length` is the length of a `str`, i.e. how many characters. This is just a quantity, so we don't count from 0. E.g. `"food".length` is 4.

### Lesson transcript

Remember "hello, world", your first program?

``````console.log("Hello, World!");
``````

As you can tell now, it's a function call, and this `console.log` function takes an argument. In this case, the argument is not a number, but a "string". This is how we call pieces of text in programming, because it's like a sequence of letters on a string.

Strings are everywhere. I'm reading this script now, and it's a text-file — a large string. The website where you're watching these videos has lots of words — all of them are strings. Google's business is remembering strings — this is what search is all about. Files and folders in your computer are identified by their names, which are strings.

Just like we did with numbers, we can create a string constant:

``````const str = "Hello";
``````

You can use single quotation marks or double quotation marks, it doesn't make a difference as long as you use the same kind in the beginning AND in the end.

If you need your string to include an actual quotation mark, then use the other kind of a mark to define the string. For example:

``````const str = 'They call him "Harry", and he likes it';
///They call him "Harry", and he likes it
``````

Here single quotation marks are used to define or surround the string, and now we're allowed to have double quotation marks inside. Or, the other way around:

``````const str = "They call him 'Harry', and he likes it";
/// They call him 'Harry', and he likes it
``````

Double on the outside, single inside.

But what if you can't do it, and you must use the same type of quotation in both the definition and in the string itself? If you just try that,

``````const str = "They call him "Harry", and he likes it";
``````

you'll get an error, because your string is broken. It stops here, because that's the second quotation mark of the same type, then you have some weird word that doesn't mean anything, then some other string. This is not valid JavaScript.

We need to tell the JavaScript interpreter that some of the quotation marks should be treated differently. They should not mean "the beginning of a string" or "the end of a string", they should mean "a symbol of a qutation mark".

This is called "escaping". Add an escape character — a backslash `\` — before the symbol, and the symbol "escapes" from its original special role and becomes a simple string character.

``````const str = "They call him \"Harry\", and he likes it";
const str2 = 'They call her \'Ann\', and she likes it';

// They call him "Harry", and he likes it
// They call her 'Ann', and she likes it
``````

This escape character can also be used to insert other special characters in a string.

``````const str = "This is a backslash \\ and here is a tab \t and here \ncomes the new line!"

// This is a backslash \ and here is a tab    and here
// comes the new line!
``````

Three things here. First: if we want a backslash character in the string, then it needs to be escaped with another backslash.

Second: backslash-t is not "escape the t character", you don't need to escape the "t", "t" is not a special character; backslash-t as a whole is a special escape-sequence — it represents a single tab, basically, a long space.

Third: backslash-n is another escape sequencerepresents a new line. It's like when you press enter while typing. So, anything that comes after will be on a new line.

Now that we have this knowledge, let's try to write a function. It will accept a string — a name and return another string — a greeting. This is how it should work:

``````const result = greet("Sherlock");   // "Well hello, Sherlock"
``````

This function must be able to somehow take the incoming string and glue it together with another string. This is called "string concatenation", and in JavaScript it's done with a plus, just like adding numbers:

``````const greet = (str) => {
return "Well hello, " + str;
}
``````

Okay, another example. This is a function that accepts a string and returns the same string but with every other letter skipped. For example, "California" becomes "Clfri".

``````const skip = (str) => {
let i = 0;
let result = '';

while (i < str.length) {
result = result + str[i];
i = i + 2;
}

return result;
}
``````

These square brackets allow us to get individual characters from a string. Like many things in programming, you start counting from 0, not from 1. So, the first character of `str` is `str[0]`, the second is `str[1]`, etc. This number is called "an index".

Function `skip` takes an argument, creates two variables — `i` for the counter, `result` for the resulting string. Counter is 0, because we want to start from the first character, and `result` is an empty string — we'll add characters to it one by one.

Then goes a while loop, with the condition being "i is less than the length of the string". Length means "how many characters". The length of the string "cats" is 4 — there are 4 characters, 4 letters.

So, while the counter is less than the length, we concatenate the resulting string with the character at index i. Then, add 2 to the counter. Two, not one, because we want to skip one character.

At some point i will become large enough for the loop condition to be false, and the function will return `result`.

Let's try it out and call this function with an argument 'cats':

``````const skipped = skip('cats');
``````

The length of 'cats' is 4. Even though indecies start with 0, the length is the actual quantity. 'c' is not 0 letters, it's one letter. So, the length of 'cats' is 4, but the index of its last letter is 3.

1. 0 is less than four, so go inside the body of the while loop
2. concatenate the result string with a character at index 0 — it's 'c'
3. increase the counter by 2
4. 2 is less than four, so repeat
5. concatenate the result string with a character at index 2 — it's 't'. the string becomes 'ct' now
6. increase the counter by 2
7. 4 is not less than 4, so don't repeat anymore
8. return result — 'ct'

The quiz and the exercise are waiting for you.

## Are there any more questions? Ask them in the Discussion section.

You will be answered by the mentors from the Hexlet team or other students.

• 115 courses, 2000+ hours of theory
• 800 practical tasks in a browser
• 250 000 students

By sending the form, you agree to "Personal Policy" and "Service Conditions".