Categories
JavaScript Basics

Using Strings in JavaScript

Spread the love

Defining Strings

It can take a few forms, like in the following code:

'string'
`string`
'日本語'

These are called string literals. The first string is a normal string. The second one is a template string literal. They are primitive values and have the type ‘string’. We can also define strings with the String function, like in the following code:

String(1)

The code above would return '1' since we convert the number 1 into a string. This can be done with all primitive values, like in the following examples:

String(true)
String('string')
String(undefined)
String(null)
String(Symbol('a'))

If we log the code above line by line, we would get:

true
string
undefined
null
Symbol(a)

However, the String method doesn’t work very well with objects like in the following code:

const str = String({
  a: 1
});
console.log(str);

The code above will get us [object Object]. However, if an object has a toString() function, then we would get something useful when using the String function to convert it to a string. For example, if we have:

const str = String({
  a: 1,
  toString(){
   return JSON.stringify(this)
  }
});
console.log(str);

console.log(String([1, 2, 3]))
console.log(String(new Date()))

Then we get:

{"a":1}
1,2,3
Sun Oct 27 2019 10:30:54 GMT-0700 (Pacific Daylight Time)

As we can see, if we added a toString() method to an object then we can get a string representation of it with the String function. This is the same with arrays and the Date object, which both have the toString() method built-in.

If we have:

console.log([1, 2, 3].toString())
console.log(new Date().toString())

Then we get the same output as in the previous example.

Escape Characters

In addition to regular printable characters, strings can also have special characters that can be escaped. The following are the escape characters that can be added into strings:

  • XXX (XXX = 1 – 3 octal digits; range of 0 – 377) — ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
  • ' — single-quote
  • " — double quote
  • “ —backslash
  • n —new line
  • r — carriage return
  • v — vertical tab
  • t — tab
  • b — backspace
  • f — form feed
  • uXXXX (XXXX = 4 hex digits; range of 0x0000 – 0xFFFF)UTF-16 code unit / Unicode code point between U+0000 and U+FFFF
  • u{X}u{XXXXXX} (X…XXXXXX = 1 – 6 hex digits; range of 0x0 – 0x10FFFF) UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF
  • xXX (XX = 2 hex digits; range of 0x00 – 0xFF)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF

Long strings can be concatenated together if they need to wrap into the next line with the + operator. For example, if we have a long string like the one below, we can write:

`let longString = "`Lorem ipsum dolor sit amet, consectetur `" +
                 "`adipiscing elit. Nulla nec facilisis libero, `" +
                 "`nec pulvinar est.`";`

More convenient ways to wrap long strings are using a slash character or use a string template literal. With the slash character, we can rewrite the string above with:

`let longString = "`Lorem ipsum dolor sit amet, consectetur   adipiscing elit. Nulla nec facilisis libero, `` nec pulvinar est.`";`

To write it with a template string, we can write:

let longString = `Lorem ipsum dolor sit amet, consectetur adipiscingelit. Nulla nec facilisis libero, nec pulvinar est.`;

Since spacing is preserved with template strings, we do not want to add extra spacing. Instead, we want to let it automatically wrap into the next line.

String Operations

We can access a character of a string by using the charAt method or using the bracket notation like accessing an entry in an array. To use the charAt method, we can write:

'dog'.charAt(1)

This would return ‘o’. Equivalently, we can use the bracket notation to get the same character as in the following code:

'dog'[1]

Which should get the same output when logged. We can’t delete or reassign a character with this notation since it’s not writable and its property descriptors can’t change, and it can’t be deleted.

To compare strings, we can use the normal comparison operators that we use like with anything else. For example, we can write:

console.log('a' < 'b');
console.log('a' > 'b');
console.log('a' == 'b');
console.log('a' === 'b');

The code above would get us:

true
false
false
false

The order is determined by the Unicode character code’s order in the list of characters or the collation specification depending on the locale. This means that the sort order may be different for different languages. String comparisons are case sensitive. For case insensitive comparisons, we have to convert them to the same case. For the best result, we should convert all the strings to uppercase since some Unicode characters don’t convert properly when converted to lowercase. For example, if we want to do case insensitive equality check then we can write:

console.log('abc'.toUpperCase() === 'Abc'.toUpperCase());

The code above would show true in the console.log .

In JavaScript, there’s also a string object, in addition to string literals. Strings can be defined with the String constructor by using the new String() constructor. With the String constructor, we get that the string will be type object even though everything else is the same. A string literal will have type string. For example, if we have the following code:

const sPrim = 'foo';
const sObj = new String(sPrim);
console.log(typeof sPrim);
console.log(typeof sObj);

The first console.log would show ‘string’ and the second one would show ‘object’. With the valueOf method, we can convert a string object into a primitive string. For example, we can write:

const sPrim = 'foo';
const sObj = new String(sPrim);
console.log(typeof sPrim);
console.log(typeof sObj.valueOf());

Then we get that both console.log statements would show ‘string’.

Basic Methods

To take full advantage of strings, we have to be able to manipulate them. Fortunately, strings have plenty of available methods to make manipulating them easy.

String.substr()

JavaScript strings have a substr function to get the substring of a string.

It takes a starting index as the first argument and a number of characters from the start index as the second argument.

It can be used like this:

const str = "Hello Bob";
const res = str.substr(1, 4); // ello

String.substring()

JavaScript strings also have a substring function that takes the start and end index as two arguments and returns a string with the ones between the start and end indices.

The start index is included but the end index is excluded.

Example:

const str = "Hello Bob";
const res = str.substring(1, 3); // el

String.toLocaleLowerCase()

Converts a string to lowercase, according to the locale of your browser. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleLowerCase(); // hello bob!

String.toLocaleUpperCase()

Converts a string to uppercase, according to the locale of your browser. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'

String.toLowerCase()

Converts a string to lowercase. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleLowerCase(); // 'hello bob!'

String.toUpperCase()

Converts a string to uppercase. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'

String.trim()

Remove starting and ending white space from a string.

For example:

const str = "         Hello Bob!     ";
const res = str.trim(); // 'Hello Bob!'

String.repeat()

To use the repeat function, you pass in the number of times you want to repeat the string as an argument. It returns a new string.

For example:

const hello = "hello";
const hello5 = A.repeat(5);
console.log(hello5); // "hellohellohellohellohello"

String.startsWith()

startsWith checks if a string starts with the substring you pass in.

For example:

const str = "Hello world.";
const hasHello = str.startsWith("Hello"); // trueconst str2 = "Hello world.";
const hasHello2 = str.startsWith("abc"); // false

String.endsWith()

endsWith checks if a string ends with the substring you pass in.

For example:

const str = "Hello world.";
const hasHello = str.endsWith("world."); // trueconst str2 = "Hello world.";
const hasHello2 = str.endsWith("abc"); // false

String.indexOf()

indexOf finds the index of the first occurrence of the substring. Returns -1 if not found.

For example:

const str = "Hello Hello.";
const hasHello = str.indexOf("Hello"); // 0
const hasHello2 = str.indexOf("abc"); // -1

String.lastIndexOf()

lastIndexOf finds the index of the last occurrence of the substring. Returns -1 if not found.

For example:

const str = "Hello Hello.";
const hasHello = str.lastIndexOf("Hello"); // 6
const hasHello2 = str.lastIndexOf("abc"); // -1

String.charAt()

charAt returns the character located at the index of the string.

For example:

const str = "Hello";
const res = str.charAt(0); // 'H'

String.search()

search gets the position of the substring passed into the function. It returns -1 if the substring is not found in the string.

Example:

const str = "Hello";
const res = str.search('H'); // 0

String.includes

includes checks if the passed-in substring is in the string. Returns true if it is in the string, false otherwise.

const str = "Hello";
const hasH = str.includes('H'); // true
const hasW = str.includes('W'); // false

String.replace()

The replace() function is useful for replacing parts of strings with another. It returns a new string with the string after the substring is replaced.

Example:

const str = "Hello Bob";
const res = str.replace("Bob", "James"); // 'Hello James'

replace() can also be used to replace all occurrences of a substring using the Regex g global property.

For example:

const str = "There are 2 chickens in fridge. I will eat chickens today.";
const res = str.replace(/chickens/g, "ducks"); // "There are 2 ducks in fridge. I will eat ducks today."

If the first argument is a regular expression that searches globally, it will replace all occurrences of the substring.

Strings are an important global object in JavaScript. It represents a sequence of characters. It can be used by various operators like comparison operators and it has methods that can manipulate them. Other important methods include searching of strings with the includes method and the indexOf method. They also have a trim() method to trim strings.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *