5 Useful Javascript String Methods


Share

JAVASCRIPT STRINGS

Javascript strings are used for storing and manipulating text. A JavaScript string is zero or more characters written inside quotes. You can use single or double quotes. You can use quotes inside a string, as long as they don't match the quotes surrounding the string.


LENGTH PROPERTY

Writing .length after a string exoression will give us the length of that strings. To find the length of a string, use the built-in length property means the length property returns the length of a string.

    let str = "thePureCodes";
    console.log(str.length);
    
    //12

CONVERTING TO UPPER CASE

A string is converted to upper case with toUpperCase(): The toUpperCase() method does not change the original string. Use the toLowerCase() method to convert a string to lowercase letters.

    let str = "javascript string!";
    let toUpper = str.toUpperCase();
    console.log(toUpper);
    
    //JAVASCRIPT STRING!

CONVERTING TO LOWER CASE

A string is converted to lower case with toLowerCase(): The toLowerCase() method does not change the original string. Use the toUpperCase() method to convert a string to uppercase letters.

    let str = "JAVASCRIPT STRING!";
    let toUpper = str.toLowerCase();
    console.log(toLower);
    
    //javascript string!

THE SEARCH METHOD

The indexOf() method returns the position of the first occurance of a specified text in a string: This method returns -1 if the value to search for never occurs.
The indexOf() method is case sensitive.

    let str = "I will be a fullstack";
    let findPos = str.indexOf("be");
    console.log(findPos);
    //7

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string: The string is searched from the end to the beginning, but returns the index starting at the beginning, at position 0. This method returns -1 if the value to search for never occurs.
The lastIndexOf() method is case sensitive!

    let str = "I will be a fullstack";
    let findPos = str.lastindexOf("be");
    console.log(findPos);
    //7

Both indexOf(), and lastIndexOf() return -1 if the text is not found.


EXTRACTING STRING CHARACTERS

The charAt() method returns the character at a specified position(index) in a string:
The index of the first character is 0, the second character is 1, and so on.

    let str = "JavaScript";
    let findChar = str.CharAt(4);
    console.log(findChar);
    //S

THE CONCAT METHOD

The concat() method makes a new string by concatenating other strings togerher:

    let text1 ="Javascript";
    let text2 = Developer;
    let text = text1.concat(" ", text2);
    console.log(text);

    /JavaScript developer!

The concat() method can be used instead of the plus operator. These two lines do the same:

    let text = "Javascript" + " " + "Developer";
    let text = "Javascript".concat(" ", "Developer");

Share Author Section