Web/JavaScript

[JavaScript] String Object

llHoYall 2022. 7. 10. 23:00

The String object is used to represent and manipulate a sequence of characters.

Create a String

The string constructor creates an instance by type coercion an argument into a string.

const strObj = new String();
const strObj = new String('HoYa');
const strObj = new String(123); // '123'

If we don't use the new operator, it is converted to a string and returned. 

String(1); // '1'
String(NaN); // 'NaN'
String(Infinity); // 'Infinity'
String(true);; // 'true'

String Property

Length

The length property of a String object contains the length of the string, in UTF-16 code units.

This property is a read-only data property of string instances.

'Hello'.length; // 5

String Method

The methods of the String object always returns a new string.

charAt()

This method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

const str = 'Hello';

str.charAt(1); // 'e'
str.charAt(10); // ''

charCodeAt()

This method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

const str = 'Hello';

str.charCodeAt(1); // 101
str.charCodeAt(10); // NaN

codePointAt()

This method returns a non-negative integer that is the Unicode code point value at the given position.

const str = 'Hello';

str.codePointAt(1); // 101
str.codePointAt(10); // undefined

concat()

This method concatenates the string arguments to the calling string and returns a new string.

const str = 'Hello';

str.concat(' World'); // 'Hello World'
str.concat(', ', 'World', ' !'); // 'Hello, World !'

endsWith()

This method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

It was introduced in ES6.

const str = 'Hello';

str.endsWith('lo'); // true
str.endsWith('z'); // false

includes()

This method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.

It was introduced in ES6.

const str = 'Hello';

str.includes('ll'); // true
str.includes('z'); // false
str.includes('l', 3); // true

indexOf()

This method searches the entire calling string, and returns the index of the first occurrence of the specified substring.

We can give a second argument as a start index to search.

const str = 'Hello';

str.indexOf('l'); // 2
str.indexOf('z'); // -1
str.indexOf('l', 3); // 3

lastIndexOf()

This method searches the entire calling string, and returns the index of the last occurrence of the specified substring.

We can give a second argument as a start index to search.

const str = 'Hello';

str.lastIndexOf('l'); // 3
str.lastIndexOf('z'); // -1
str.lastIndexOf('l', 2); // 2

match()

This method retrieves the result of matching a string against a regular expression.

'Target string'.match(/pattern/);

matchAll()

This method returns an iterator of all results matching a string against a regular expression, including capturing groups.

'Target string'.matchAll(/pattern/);

padEnd()

This method pads the current string with a given string so that the result string reaches a given length.

const str = 'Hello';

str.padEnd(10); // 'Hello     '
str.padEnd(10, '.'); // 'Hello.....'

padStart()

This method pads the current string with another string until the resulting string reaches the given length.

const str = 'Hello';

str.padStart(10); // '     Hello'
str.padStart(10, '.'); // '.....Hello'

raw()

This static method is a tag function of template literals.

const str = String.raw`Hello\World`;

console.log(str); // Hello\World

repeat()

This method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

It was introduced in ES6.

const str = 'Hello';

str.repeat(); // '' (same as 0)
str.repeat(1); // 'Hello'
str.repeat(3); // 'HelloHelloHello'
str.repeat(2.5); // 'HelloHello' (truncate to 2)
str.repeat(-2); // RangeError: Invalid count value

replace()

This method returns a new string with some or all matches of a pattern replaced by a replacement.

const str = 'Hello World';

str.replace('World', 'HoYa'); // 'Hello HoYa'
str.replace('o', 'a'); // 'Hella World' (changed only one)
str.replace(/ll/gi, 'n'); // 'Heno World'

replaceAll()

This method returns a new string with all matches of a pattern replaced by a replacement.

const str = 'Hello World';

str.replaceAll('o', 'a'); // 'Hella Warld'

search()

This method executes a search for a match between a regular expression and this String object.

const str = 'Hello World';

str.search(/o\b/); // 4
str.search(/o/); // 4
str.search(/z/); // -1

slice()

This method extracts a section of a string and returns it as a new string, without modifying the original string.

const str = 'Hello';

str.slice(1, 3); // 'el'
str.slice(2); // 'llo'
str.slice(-2); // 'lo' (last 2 characters)
str.slice(10); // ''

split()

This method takes a pattern and divides a String into an ordered list of substring by searching for the pattern, puts these substrings into an array, and returns the array.

const str = 'Hello World';

str.split(' '); // ['Hello', 'World']
str.split(/\s/); // ['Hello', 'World']
str.split(''); // ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
str.split(); // ['Hello World']
str.split(' ', 1); // ['Hello'] (1 element)

startsWith()

This method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

It was introduced in ES6.

const str = 'Hello';

str.startsWith('Hell'); // true
str.startsWith('z'); // false

substring()

This method returns the part of the string between the start and end indexed, or to the end of the string.

const str = 'Hello World';

str.substring(2, 4); // 'll'
str.substring(5, 3); // 'lo' (exchange arguments)
str.substring(3, 100); // 'lo World'
str.substring(5); // ' World'
str.substring(-3); // 'Hello World' (same as 0)
str.substring(100); // ''

toLowerCase()

This method returns the calling string value converted to lower case.

const str = 'Hello';

str.toLowerCase(); // 'hello'

toString()

This method returns a string representing the specified object.

const str = new String('Hello');

str.toString(); // 'Hello'

toUpperCase()

This method returns the calling string value converted to upper case.

const str = 'Hello';

str.toUpperCase(); // 'HELLO'

Trim Methods

These methods remove whitespace from one or both ends of a string and return a new string, without modifying the original string.

const str = '  Hello   ';

str.trim(); // 'Hello'
str.trimStart(); // 'Hello   ';
str.trimEnd(); // '  Hello';