JavaScript Strings methods

Here are 10 String methods one should learn as a beginner in JavaScript: no strings attached

ยท

5 min read

JavaScript Strings methods

Strings are a data type in JavaScript (written within 'single'/"double" quotes). We can perform some basic operations on strings using in-built methods. Let's dive straight into them.


๐Ÿฆ„ 1) str.length

As you can understand from the name, the .length method using which we can get the count of the characters in a string.

const name = "John Doe"
console.log(name.length);  // 8

console.log('JavaScript'.length);  // 10

Note: Unlike other languages where the length property is called using parenthesis (string.length()), in JavaScript we just mention the method name without ()


๐Ÿฆ„ 2. str.indexOf & str.lastIndexOf

The first method is helpful to find a substring's position within a string.

Syntax: str.indexOf('substr', pos);

const str = 'Hello World';
str.indexOf('e');  // 1
str.indexOf('o');  // 4

// Above tells index of the first occurrence of the substring
// We can also find position from specified positions
str.indexOf('l', 5)  // 9

Remember the indexing of characters in strings starts from 0, not 1

Using the second method, we can find the position of the last occurrence of a substring within the string.

const str = 'Oranges are orange'
str.lastIndexOf('or');  // 12

๐Ÿฆ„ 3. str.slice

This method is useful to extract a substring from the parent string.

Syntax: str.slice(startPosition, endPosition)

This gives you the substring from startPosition till (not including) endPosition.

const address = "03, Light Avenue, NY";
address.slice(0, 2);  // '03'

/* to print till the end of string */
address.slice(4);  // 'Light Avenue, NY'

/* You can use the method directly on Strings */
"John Doe".slice(5);  // 'Doe'

.slice method also takes negative values, which displays values from the end of the string to mentioned position.

/* prints last 3 charaters */
"John Doe".slice(-3);  // 'Doe'

"4:30".slice(-2);  // '30'

๐Ÿฆ„ 4. str.toLowerCase() & str.toUpperCase()

Want to change the case of your string? Use these methods to do so.

const str = 'Oranges are orange';
str.toLowerCase()  // 'oranges are orange'
str.toUpperCase()  // 'ORANGES ARE ORANGE'

Though converting cases is quite common, there are times when we want to capitalize only the first letter in the string (such as for names). Here's how you can do it. (Though there are more than one way of doing this, here's one)

// convert 'joHn' to 'John'
const name = 'joHn';
const newName = name[0].toUpperCase() + name.slice(1).toLowerCase();
console.log(newName);  // John

๐Ÿฆ„ 5. str.trim()

A lot of times the string entered by the user might contain whitespaces and special characters that we want to get rid of, for further use. This method does exactly that.

const str = '     Hello World \n';
str.trim();  // 'Hello World'
/* The white spaces at start of string is removed, as well as the special newline charated \n*/

๐Ÿฆ„ 6. Boolean methods: .includes , .startsWith, .endsWith

These are some methods using with which we can find out if a certain substring is part of the parent string. They return boolean true and false accordingly.

Syntax:

  • str.includes(substring)
  • str.startsWith(substring)
  • str.endsWith(substring)
const address = "03, Light Avenue, NY";
address.includes('NY');  // true
address.startsWith('03')  // true
address.endsWith('LA')  // false

๐Ÿฆ„ 7. str.replace & str.replaceAll

As indicated by the name, we can replace parts of the strings using this method.

Syntax: str.replace('from', 'to')

const line = 'An orange a day keeps the doctor away'
line.replace('orange', 'apple');  // 'An apple a day keeps the doctor away'

const word = 'Hello World';
word.replaceAll('o', 'e');  // 'Helle Werld'

( Well, you can make better use of replaceAll unlike me ๐Ÿ˜†)


๐Ÿฆ„ 8. Splitting and Joining strings: str.split & str.join

The split() method splits a string into an array of substrings and returns the new array. The () is used to specify a separator at which the strings should be separated.

Syntax: str.split(separator)

'hello'.split("");  
     // ['h', 'e', 'l', 'l', 'o']

'I am learning JavaScript'.split(" ");  
    // ['I', 'am', 'learning', 'JavaScript']

Whereas the join() returns an array as a string. The () is used to specify the separator at which array elements should be joined. The default separator is comma (,).

Syntax: str.join(separator)

const newArray = ['I', 'am', 'learning', 'JavaScript'];
newArray.join(" ");  // 'I am learning JavaScript'

const names = [ 'James', 'Riya', 'Zakir', 'Ganesh'];
names.join(", ");   // 'James, Riya, Zakir, Ganesh'

๐Ÿฆ„ 9. str.repeat

As indicated by the name, you can repeat certain strings a number of times using this method.

Syntax: str.repear(count)

'Be Kind โค '.repeat(2);
     //  'Be Kind โค Be Kind โค '

๐Ÿฆ„ 10. str.concat

The concat() method joins two or more strings.

let str1 = "gracias ";
let str2 = "mi amigo!";
str1.concat(str2);  // 'gracias mi amigo!'

Points to note:

  • We can use multiple methods on a single string as well
  • We can use most of these methods directly on strings
  • String methods do not change the original string

JavaScript has a lot of string methods, and I have only covered some important ones one should know as a beginner. You can check out MDN Docs for knowing more about strings and its methods.


That was it for this blog post! Hopefully, you found the article to be useful! I would be happy to receive your feedback in the comments ๐Ÿ˜Š

You can always connect with me at Twitter | LinkedIn โœจ

ย