Today I Learned JavaScript String Methods



This content originally appeared on DEV Community and was authored by SEENUVASAN P

Javascript strings are primitive and immutable: All string methods produce a new string without altering the original string

String concat()
String trim()
String trimStart()
String trimEnd()
String padStart()
String padEnd()
String repeat()
String toUppercase()
String toLowercase()
String charAT()

1. String concat()

Concat used to add two are more string.

Example:

let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
console.log(text3);

Output:

Hello world

2.String trim()

Trim is used to remove the around space of the string.

Example:

let text1 = "      Hello World!      ";
console.log(text1.length)
let text2 = text1.trim();
console.log(text2);
console.log(text2.length)

Output:

 30
 Hello World
 12

3.String.trimStart()

This method removes whitespace only from the start of the string.

Example:

let text = "     Hello!";
let trimmed = text.trimStart();
console.log(trimmed); // "Hello!"

4.String.trimEnd()

This removes whitespace only from the end of the string.

Example:

let text = "Hello!     ";
let trimmed = text.trimEnd();
console.log(trimmed); // "Hello!"

5.String.padStart()

It pads the current string with another string (repeated) until it reaches the given length, starting from the beginning.

Example:

let number = "5";
let padded = number.padStart(4, "0");
console.log(padded); // "0005"

6.String.padEnd()

This is similar to padStart(), but padding is added at the end.

Example:

let number = "5";
let padded = number.padEnd(4, "0");
console.log(padded); // "5000"

7.String.repeat()

It returns a new string with a specified number of copies of the string.

Example:

let word = "Hi ";
let repeated = word.repeat(3);
console.log(repeated); // "Hi Hi Hi "

8.String.toUpperCase()

It converts the string to uppercase.

Example:

let text = "hello";
console.log(text.toUpperCase()); // "HELLO"

9.String.toLowerCase()

It converts the string to lowercase.

Example:

let text = "HELLO";
console.log(text.toLowerCase()); // "hello"

10.String.charAt()

It returns the character at a specified index.

Example:

let text = "JavaScript";
console.log(text.charAt(4)); // "S"

Reference:

https://www.w3schools.com/js/js_string_methods.asp#mark_trim


This content originally appeared on DEV Community and was authored by SEENUVASAN P