Strings In-depth

Creating String

String Literals

Most of the time you will create string as literals.

let str = "Hello";

But, like an Array, you can create a string by using the String constructor.

let str = "Hello";
console.log(str);
console.log(typeof(str));

str = new String("Hello");
console.log(str);
console.log(typeof(str));

str = String("Hello");
console.log(str);
console.log(typeof(str));

It's interesting to look at the output of these three cases in the debugger. The second case shows an object with an internal array that has a length of 5. The other two cases return a literal string.

You can use the String constructor to convert a different type to a string. It doesn't work to convert an object, except for an array of primitive types.

Operators

Assignment

We learned in the introduction to the String object that you can concatenate string. We can also use the assignment operator to concatenate.

Comparison

You can compare two strings, based on their ascii codes.

Conversion

Methods

Here are a few example. There are more, but the are all pretty straight forward to use and easy to look up so I'll just link to the documentation.

Splitting a string into an array

Finding the Index Of a sub string in a string

Returns the index of the first occurrence of the sub string in the string. If the sub string cannot be found, -1 will be returned.

You can pass the start index as the second parameter.

Return a section of the string

Last updated

Was this helpful?