DEV Community

SEENUVASAN P
SEENUVASAN P

Posted on

Today I Learned JavaScript String Methods

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()
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output:

Hello world
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

 30
 Hello World
 12
Enter fullscreen mode Exit fullscreen mode

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!"
Enter fullscreen mode Exit fullscreen mode

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!"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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 "
Enter fullscreen mode Exit fullscreen mode

8.String.toUpperCase()

It converts the string to uppercase.

Example:

let text = "hello";
console.log(text.toUpperCase()); // "HELLO"
Enter fullscreen mode Exit fullscreen mode

9.String.toLowerCase()

It converts the string to lowercase.

Example:

let text = "HELLO";
console.log(text.toLowerCase()); // "hello"
Enter fullscreen mode Exit fullscreen mode

10.String.charAt()

It returns the character at a specified index.

Example:

let text = "JavaScript";
console.log(text.charAt(4)); // "S"
Enter fullscreen mode Exit fullscreen mode

Reference:

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

Top comments (0)