Building JavaScript String methods from Scratch

Strings in Javascript are used to represent text data. There are several methods available to manipulate them. We will be building some of these string methods from scratch in JavaScript. The idea behind that is, to grasp the concept and learn how these methods work internally.

The methods we will be focusing on are

  • charAt()
  • concat()
  • toUpperCase()
  • toLowerCase()
  • substring()

 

String.prototype.charAt()

The charAt() is a string object method that takes the index as an argument. Therefore, using that index, it returns the corresponding character in the string present at that index position.

str = 'Hello World'
character = str.charAt(6)
console.log(character)
W

 

Building charAt() from scratch

This is a simple straightforward implementation. Javascript string also works like an array-like object. Therefore we can access the individual characters using their index value. In the below example, we take the index value as some integer say 6. Then we print the corresponding character by using square brackets.

str = 'Hello World'
index = 6
console.log(str[index])
W

 

String.prototype.concat()

The concat() method concatenates the calling string to the arguments passed to it as the string.

str1 = 'Hello'
str2 = 'World'
console.log(str1.concat(', ', str2))
console.log(str1.concat(', ', 'super ', str2))
Hello, World
Hello, super World

 

Building concat() from scratch

In the below example, we have defined a function that takes any number of arguments and store it as an array. We iterate through the array and append each string to a new variable. Appending is achieved by using the ‘+’ operator. At last, we return the concatenated string.

 

function concat(...str) {
    concat_str = ''
    for (i in str) {
        concat_str += str[i]
    }
    return concat_str
}

console.log(concat('Hello', ', ', 'World'))
console.log(concat('Hello', ', ', 'super ', 'World'))
Hello, World
Hello, super World

 

String.prototype.toUpperCase()

This method converts the given string to uppercase and returns the value. It does not affect the original string.

str = 'Hello World'
upper = str.toUpperCase()

console.log(upper)
HELLO WORLD

 

Building toUpperCase() from scratch

Here we declare a function that takes a string. We iterate through each character present in the string. If the character’s ASCII is between 97 and 122, that is, lowercase then we change it uppercase by subtracting 32 from it. Else we keep it as it is and append it to another string. We use charCodeAt() and fromCharCode() methods of javascript strings to convert to and from ASCII respectively.

function toUpperCase(str) {
    upper = ''
    for (i in str) {
        if (str.charCodeAt(i) > 96 && str.charCodeAt(i) < 123) {
            upper += String.fromCharCode(str.charCodeAt(i) - 32)
        } else {
            upper += str[i]
        }
    }
    return upper
}

str = 'Hello World'
console.log(toUpperCase(str))
HELLO WORLD

 

String.prototype.toLowerCase()

This method converts the given string to lowercase and returns the value. It does not affect the original string.

str = 'Hello World'
lower = str.toLowerCase()

console.log(lower)
hello world

 

Building toLowerCase() from scratch

Here we declare a function that takes a string. We iterate through each character present in the string. If the character’s ASCII is between 65 and 90, that is, uppercase then we change it lowercase by adding 32 to it. Else we keep it as it is and append it to another string. We use charCodeAt() and fromCharCode() methods of javascript strings to convert to and from ASCII respectively.

function toLowerCase(str) {
    lower = ''
    for (i in str) {
        if (str.charCodeAt(i) > 64 && str.charCodeAt(i) < 91) {
            lower += String.fromCharCode(str.charCodeAt(i) + 32)
        } else {
            lower += str[i]
        }
    }
    return lower
}

str = 'Hello World'
console.log(toLowerCase(str))
hello world

 

String.prototype.substring()

The substring() takes two integer arguments. They are the start and end indices. The method extracts the string from the start index (inclusive) and end index (exclusive). If only one argument is passed, then from that index till the end of the string is extracted and returned.

str = 'Hello World'
console.log(str.substring(2, 9))
console.log(str.substring(3))
llo Wor
lo World

 

Building substring() from scratch

Here we declare a function that takes 3 arguments. They are the string, start index, and end index. We iterate through the loop from the start index and end index and add the corresponding characters to another variable. Finally, we return the variable.

function substring(str, start, end = -1) {
    if (end == -1) {
        end = str.length
    }
    if (start > end) {
        start = start + end
        end = start - end
        start = start - end
    }

    substr = ''
    for (i = start; i < end; i++) {
        substr += str[i]
    }
    return substr
}

str = 'Hello World'
console.log(substring(str, 2, 9))
console.log(substring(str, 3))
llo Wor
lo World

 

Please post your comments, doubts, queries in the comment box. Happy Learning 🙂

Also, read

Leave a Reply

Your email address will not be published. Required fields are marked *