DEV Community

Cover image for Built-in String functions in JavaScript
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Updated on • Originally published at learn.coderslang.com

Built-in String functions in JavaScript

In JavaScript, all text data is a String. It doesn’t matter if there’s 1 char or 10k lines, it’s still a String.

This article is also available here

Before we get to the review of the built-in String functions, take a note that the length of all JS strings is stored in the length property.

You can access it directly and don’t have to call any specific getter method.

const s = 'Hello, World!';
console.log(s.length);
Enter fullscreen mode Exit fullscreen mode

The second important point, that deserves its own quote is

All strings in JS are immutable.

Once a string is created, it will never be changed. Functions like replace or slice, will always return a new string, but the original one will be left intact.

A comprehensive list of String functions in JS

For demonstration purposes I’ll assume we have some string s declared as a constant with the value I am going to become a FULL STACK JS Dev with Coderslang. Further, I’ll list some ideas that we might want to apply to this string and ways to do this.

const s = 'I am going to become a FULL STACK JS Dev with Coderslang';
Enter fullscreen mode Exit fullscreen mode

How to check if a string includes another string

To check if our string contains another string, we should use the includes function. It will return true or false based on the result of the check.

console.log(s.includes('FULL STACK'));     // true
console.log(s.includes('cheeseburger'));   // false
Enter fullscreen mode Exit fullscreen mode

Another way of doing this is by using the indexOf or lastIndexOf functions. Both of them will lookup if the string contains another string and returns the index of the beginning of the match. If no match is found, it means that the original string doesn’t include the search string and the result will be -1;

console.log(s.indexOf('AWS'));             // -1
console.log(s.lastIndexOf('AWS'));         // -1
Enter fullscreen mode Exit fullscreen mode

The difference between indexOf and lastIndexOf becomes evident when there are multiple matches inside the string.

console.log(s.indexOf('g'));               // 5
console.log(s.lastIndexOf('g'));           // 55
Enter fullscreen mode Exit fullscreen mode
  • indexOf starts the lookup from the beginning
  • lastIndexOf starts the lookup from the end

This determines the difference in the result.

In any case, we can use both indexOf and lastIndexOf functions to determine if one string includes another one in JavaScript. If the result is anything other than -1, then it does. Otherwise, it doesn’t.

How to determine if one string starts with another string

To check if a string starts with another string, there’s a startsWith function. It returns true if our string starts with another string or false if it doesn’t.

console.log(s.startsWith('I am'));             // true
console.log(s.startsWith('You are'));          // false
Enter fullscreen mode Exit fullscreen mode

How to determine if one string ends with another string

To check if a string ends with another string, there’s an endsWith function. It works almost the same way as startsWith, but it checks the end of the string, not the start.

console.log(s.endsWith('Coderslang'));          // true
console.log(s.endsWith('Node.js'));             // false
Enter fullscreen mode Exit fullscreen mode

How to remove spaces at the beginning of the end of the string

To remove the whitespace at the start or the end of the string, you can use these functions:

  • trimStart - to remove spaces at the beginning of the string
  • trimEnd - to remove spaces at the end of the string
  • trim - to do both actions at once and remove leading and trailing whitespace

Our base string won’t suffice to demonstrate this example, so we’ll create another one.

const stringWithSpaces = '   I learn JS with Coderslang every day   ';
console.log(stringWithSpaces.trimStart());  //'I learn JS with Coderslang every day   '
console.log(stringWithSpaces.trimEnd());    //'   I learn JS with Coderslang every day'
console.log(stringWithSpaces.trim());       //'I learn JS with Coderslang every day'
Enter fullscreen mode Exit fullscreen mode

How to convert a string to the UPPERCASE or the lowercase

To change all characters of the string to the uppercase you can use the function toUpperCase and for the lowercase, you can use toLowerCase.

console.log(s.toUpperCase());  // I AM GOING TO BECOME A FULL STACK JS DEV WITH CODERSLANG
console.log(s.toLowerCase());  // i am going to become a full stack js dev with coderslang
Enter fullscreen mode Exit fullscreen mode

Once again, notice that the original string never changes, as strings are immutable in JavaScript. These functions just return a new string with the desired changes.

How to replace a character in a string with a different one

To replace a character with another one in JS, you can use the replace function. Pass it two strings, and it will replace the first string with the second one.

console.log(s.replace(' ', '!')) // I!am going to become a FULL STACK JS Dev with Coderslang
console.log(s.replace('I am', 'You are')) // You are going to become a FULL STACK JS Dev with Coderslang
Enter fullscreen mode Exit fullscreen mode

You might be surprised with the result as replace was applied only once. But that’s how it works in the base case.

If you want to change all occurrences of a substring, you should use the replaceAll function.

console.log(s.replaceAll(' ', '!')) // I!am!going!to!become!a!FULL!STACK!JS!Dev!with!Coderslang
Enter fullscreen mode Exit fullscreen mode

Take a note, that depending on your javascript runtime environment, you might run into the error

TypeError: s.replaceAll is not a function

If you do, then replaceAll isn’t supported in your environment and you can either implement it yourself or use a regular expression with the g flag. This will instruct replace to be applied globally.

const regex = new RegExp(' ', 'g');
const s = 'I am going to become a FULL STACK JS Dev with Coderslang';

console.log(s.replace(regex, '!')); // I!am!going!to!become!a!FULL!STACK!JS!Dev!with!Coderslang
Enter fullscreen mode Exit fullscreen mode

Regular expressions are a very powerful tool, so make sure to learn them if you haven’t already.


That concludes the review of the most useful built-in String functions in JS. Is there something else you want to add to this article or maybe request a new one?

Learn Full Stack JavaScript

Top comments (1)

Collapse
 
ypedroo profile image
Ynoa Pedro

Awesome article man, congatulations!