String it on: Mastering JavaScript Strings Methods...!

String it on: Mastering JavaScript Strings Methods...!

A Guide to JavaScript String Methods and Manipulation.

ยท

7 min read

A string is a sequence of characters. It contains zero or more characters within single (' '), double (" "), or backticks (``). Strings can contain letters, numbers, symbols, and special characters.

We have studied strings in the previous blog. Let us dive deeply into the methods of JavaScript strings.

String Length

It returns the number of characters in the string. This is read-only.

const languageName = "JavaScript";
console.log(`String is "${languageName}" and the length is 
${languageName.length}`);
/*
    OUTPUT
    String is "JavaScript" and the length is 10
*/

Character Access

A character can be accessed in 3 ways.

  1. string[index] - Treating string as array-like an object

  2. at(index)

  3. charAt(index)

  4. charCodeAt(index)

string[index]

It returns the character at the specified index. Can't access using a negative index.

const languageName = "JavaScript";
console.log(languageName[0]);
console.log(languageName[3]);
/*
    OUTPUT

    J
    a
*/

at(index)

Returns the character at the specified index. It takes both positive and negative integers.

The positive index starts from the beginning and the negative index starts from the back of the last string character. The positive index starts from 0 and the negative index starts from -1.

const study = "Welcome to JavaScript";
console.log(study.at(3));
console.log(study.at(-1));
/*
    OUTPUT

    c
    t
*/

charAt(index)

The charAt() Returns the character at the specified index. It can't be accessed using a negative index.

const study = "Welcome to JavaScript";
console.log(study.charAt(5));
/*
    OUTPUT
    m
*/

charCodeAt(index)

The charCodeAt() method returns the code of the character at a specified index in a string:

The method returns a UTF-16 code (an integer between 0 and 65535).

const lang = "JavaScript";
console.log(lang.charCodeAt(1));
/*
    OUTPUT

    97
*/

String Methods

concat()

The conact() method is used to combine two or more strings without changing the original strings and returning a new one.

const learn = "Learn";
const lang = "JavaScript";
const space = "for Web Dev, App Dev, Backend etc";
console.log(learn.concat(" ", lang, " ", space));

//joining 2 or more strings using string interpolation
const myName = "K Subramanyeshwara";
const learning = "JavaScript";
console.log(`My name is ${myName} and I am learning ${learning}`);
/*
    output

    Learn JavaScript for Web Dev, App Dev, Backend etc
    My name is K Subramanyeshwara and I am learning JavaScript
*/

toLowerCase()

The toLowerCase() method converts the entire string to lowercase.

const learning = "FRONteND"
console.log(learning.toLowerCase());
/*
    OUTPUT

    frontend
*/

toUpperCase()

The toUpperCase() method converts the entire string to uppercase.

const world = "hello world";
console.log(world.toUpperCase());
/*
    OUTPUT
    HELLO WORLD
*/

startsWith()

It checks whether a string begins with specified character(s). Returns true if the string starts with the specified character(s), and false otherwise. It is case-sensitive.

string.startsWith(searchString, position);

searchString: The characters to be searched for at the start of the string.

position (optional): The position from where searching begins for searchString. Defaults to 0.

const str = "To be, or not to be, that is the question.";
console.log(str.startsWith('To'))
console.log(str.startsWith('to'))
console.log(str.startsWith('to', 14))
console.log(str.startsWith('not to be'));
console.log(str.startsWith('not to be', 10));
/*
    OUTPUT

    true
    false
    true
    false
    true
*/

endsWith()

It checks whether a string ends with specified character(s). Returns true if the string ends with the specified character(s), and false otherwise. It is case-sensitive.

string.endsWith(searchString, endPosition);

searchString: The characters to be searched for at the start of the string.

endPosition: The position from where searching ends for searchString.

const sentence = 'Java is to JavaScript what Car is to Carpet';
console.log(sentence.endsWith('Carpet'));
console.log(sentence.endsWith('carpet'));
console.log(sentence.endsWith('a', 2));
console.log(sentence.endsWith('a', 15));
/*
    OUTPUT

    true
    false
    true
    true
*/

replace()

It replaces a part of the given string with another character(s) or a regular expression. It will not alter the original string.

string.replace(pattern, replacement);

const url = "https://www.subramanya.com/subramanya%219ishwara";
console.log(url);
const updatedUrl = url.replace("%219", "--");
console.log(updatedUrl);
console.log(url);
/*
    OUTPUT

    https://www.subramanya.com/subramanya%219ishwara
    https://www.subramanya.com/subramanya_ishwara
    https://www.subramanya.com/subramanya%219ishwara
*/

replaceAll()

Returns a new string after replacing all the matches of a string with a specified character(s)/regex.

string.replaceAll(pattern, replacement);

const str = "Happy holidays, everyone!";
const newStr = str.replaceAll("holidays", "seasons");
console.log(newStr);
/*
    OUTPUT

    "Happy seasons, everyone!"
*/

indexOf()

To find the index/position of the first occurrence of a substring in a string.

It searches the string and returns the index of the first occurrence of the specified searchString if the position is not specified. If the position is specified, it returns the first occurrence searchString after the position is given.

If the occurrence is not found then -1 will be returned. It will not take a negative index.

string.indexOf(searchString, position);

let documentName = 'Mozilla Developer Network(MDN)'
console.log(documentName.indexOf("o"));
console.log(documentName.indexOf("e"));
console.log(documentName.indexOf("N"));
const paragraph = 'The quick brown fox jumps over the lazy dog. 
If the dog barked, was it really lazy dog?';
console.log(paragraph.indexOf('lazy dog'))
console.log(paragraph.indexOf('dog'))
console.log(paragraph.indexOf('dog', 45))
/*
    OUTPUT

    1
    9
    18
    35
    40
    52
*/

lastIndexOf()

To find the index/position of the last occurrence of a substring in a string.

It searches the string and returns the index of the last occurrence of the specified substring. The lastIndexOf() method is case-sensitive.

It returns the index of the last occurrence of searchString. If the occurrence is not found then -1 will be returned.

string.lastIndexOf(searchString, position);

let str = "Learning String and String methods";
console.log(str.lastIndexOf("String", 15));
console.log(str.lastIndexOf("String"));
console.log(str.lastIndexOf('string'))

/*
    OUTPUT

    9
    20
    -1
*/

includes()

It is used to determine if a particular substring exists within a given string. Returns true if the string contains the substring, otherwise, it returns false. It is case-sensitive.

string.includes(searchString, position);

searchString: You provide a string (the substring) that you want to check for within the larger string.

position: The default starting position is 0. You can also specify the starting position.

const languageName = 'JavaScript';
console.log(languageName.includes("Scri"));
console.log(languageName.includes("scri"));
console.log(languageName.includes('a', 2));
console.log(languageName.includes("asd"));
/*
    OUTPUT

    true
    false
    true
    false
*/

trim()

Remove the white spaces (spaces, tabs, newlines) from both ends of the given string and return a new string, without modifying the original string. It does not change the original string.

trim()

let newString = "     Subramanya    ";
console.log(newString);
console.log(newString.trim());
/*
    OUTPUT
        Subramanya
    Subramanya
*/

trimEnd()

It removes whitespace (spaces, tabs, newlines) from the end of the string, without modifying the original string.

trimEnd()

let newString = "     Subramanya    ";
console.log(newString);
console.log(newString.trimEnd());
/*
    OUTPUT

        Subramanya
        Subramanya

*/

trimStart()

It removes whitespace (spaces, tabs, newlines) from the beginning (start) of the string, without modifying the original string.

trimStart()

let newString = "     Subramanya    ";
console.log(newString);
console.log(newString.trimStart());
/*
    OUTPUT
        Subramanya
    Subramanya
*/

slice()

It is used to extract a section of a string and return it as a new string, without modifying the original string.

slice(startIndex, endIndex)

startIndex (required): The index at which to begin extraction. Zero-based indexing is used, meaning the first character is at index 0.

endIndex (optional): The ending index of the substring (exclusive). If omitted, the slice extends to the end of the string.

  • If startIndex is negative, it counts backwards from the end of the string.

  • If endIndex is negative, it counts backwards from the end of the string.

  • If startIndex is greater than or equal to the string length, an empty string is returned.

  • If endIndex is less than startIndex, the extracted string will be empty.

const str1 = 'The quick brown fox jumps over the lazy dog.';
console.log(str1.slice(31));
console.log(str1.slice(4, 19));
console.log(str1.slice(-4));
console.log(str1.slice(-9, -5));
console.log(str1.slice(0));
/*
    OUTPUT

    the lazy dog.
    quick brown fox
    dog.
    lazy
*/
const str1 = "The morning is upon us.";
//start index is -11(count starts from the end) and includes the starting index and the end index is 16(count starts from the beginning) and excludes the end index.
console.log(str1.slice(-11, 16)); // "is u"
//start index is 5(count starts from the beginning)and  includes the starting index and the end index is -9(count starts from the end) and excludes the end index
console.log(str1.slice(5, -9));
/*
    OUTPUT

    is u
    orning is
*/
let fullName = "Snoop Dogg werfwer";
console.log(fullName.slice(0, fullName.indexOf(" ")));
console.log(fullName.slice(fullName.indexOf(" ") + 1));
console.log(fullName.slice(0, fullName.indexOf('g')))
/*
    OUTPUT

    Snoop
    Dogg werfwer
    Snoop Do
*/

Conclusion

In this article, we have covered

Character access and

Different string methods.

We have not discussed RegEx which I will cover in an upcoming article, Stay tuned for that.

Thank you for taking the time to read this article ๐Ÿ˜Š. I hope the article provided you with valuable insights. I would highly appreciate it if you take a moment to like ๐Ÿ‘, share your thoughts or feedback comment โœ๏ธ, and share ๐Ÿ” it.

Happy Learning...! โœŒ๏ธโœŒ๏ธโœŒ๏ธ

If you liked my content, Connect with me on,

Did you find this article valuable?

Support K Subramanyeshwara by becoming a sponsor. Any amount is appreciated!

ย