Computer scienceProgramming languagesJavaScriptWorking with dataStrings

String transforming

5 minutes read

You already know what strings are and how to use them. But what you haven't been shown yet is how to transform a string. Operations like dividing it into several pieces, converting its letters to upper or lowercase, and more. In this topic, you will learn about the methods used to perform these important tasks.

Changing the case

The first two methods on the list are toUpperCase() and toLowerCase(). As their names suggest, they allow you to convert all the letters within a string to either upper or lowercase. This often comes in handy. For example, you might want to change a DOM element's content to match the lowercase text used in the rest of a page.

Both methods are called in the way you would expect:

let mystring = 'HYPERSKILL';
console.log(mystring.toLowerCase()); // hyperskill

mystring = 'hyperskill';
console.log(mystring.toUpperCase()); // HYPERSKILL

These methods don't accept any other arguments and do not change the value of the initial variable. Instead, they return a new transformed version of the string that you can either save into a variable or log to the console.

Removing extra spaces

Users typically don't care if there are extra spaces around their email addresses when they're entering them to create an account — they expect your website to trim them out automatically. The same applies to all form fields and in many other scenarios. So, the responsibility for removing extra space at the beginning and end of any user-supplied text rests on your shoulders.

To perform this task, you could run a loop that removes the first item from the string while it's equal to the space character (' '). Then you could run another loop to remove the spaces at the end. However, a better alternative is to use the trim() method, which allows you to achieve the same result with a single line of code:

let user_email = '    [email protected]        ';
console.log(user_email.trim()); // [email protected]

As with the methods in the previous section, it's important to keep in mind that trim() doesn't change the original string. This means that if you execute the following code:

let user_email = '    [email protected]        ';
user_email.trim();
console.log(user_email); //     [email protected]        

You'll still see a string with extra spaces.

Repeating a string

There are times when it can be useful to generate a new string by repeating an original string several times. You can do this with a for loop that concatenates two strings together repeatedly:

let mystring = 'text ';
let result = '';

for(let i = 0; i < 5; i++) {
    result = result + mystring;
}

console.log(result); // text text text text text 

The above may not look very complicated, but why use so many lines of code when JavaScript has a tool designed specifically for the job? The simplest way to achieve this goal is by using the repeat() method, as shown below:

let mystring = 'text ';
let result = mystring.repeat(5);
console.log(result); // text text text text text 

It's as easy as that! Remember that this method doesn't change the initial string either — it returns a transformed string that you can save to a variable or log to the console.

Finding a substring

Sometimes you receive a really long string and need to cut it into pieces so you can extract the parts that make sense. So how can this processing be done? Well, provided you know the indices of each of the substrings you require, the substring() method can help. It accepts two arguments — the index numbers of the first and last symbols that form the substring. Under the hood, it extracts all the characters between the index positions and returns a new string. Here's a quick example:

let mystring = 'Sample text';
console.log(mystring.substring(0, 6)); // Sample

Notice that the letter in the last index position is not included in the range. That's why the index numbers 0 and 6 are specified in the above example, instead of 0 and 5. You can see what happens if you don't take this into account below:

let mystring = 'Sample text';
console.log(mystring.substring(0, 5)); // Sampl

You can also pass substring() a single argument. If you take this approach, the method will return a substring from the starting position until the end of the string:

let mystring = 'Sample text';
console.log(mystring.substring(3)); // ple text

Some other points that you need to consider when using this method are listed below:

  • If the first argument has a higher value than the second, JavaScript automatically switches them.

  • If either argument is less than or equal to 0, or if a NaN value is used, it's treated as 0.

  • Lastly, if either argument is greater than the length of the string, it's considered equal to the length of the string.

You may also encounter a similar method called substr(). Like substring(), this method takes two arguments (and the second one is optional as well). However, while the first argument is still the index where the substring begins, the second is the length of the required substring instead of the end position:

let mystring = 'Sample text';
console.log(mystring.substr(3, 5)); // ple t

Be aware that the substr() method is deprecated though some browsers might still support it. So you should avoid using it if possible.

Conclusion

In this topic, you have discovered more about the power of strings. You've learned how to transform them by using some of the most common string methods, and that this only requires a single line of code. You now know how to change a string's letters to upper or lowercase, trim away unnecessary space, repeat a string multiple times, and extract substrings. Enjoy!

87 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo