During the coding interview, many problems comes with the string manipulations. In this article, I want to review some string methods that can be useful for the coding interview.
String Length
str.length
Access Character
Find specific character by index
let str = “hello world”;
console.log(str.charAt(0));
console.log(str[0]);
// both above’s result are the same: h
Character or string exists
let str = “hello world”;
// true
console.log(str.includes(“he”);
// true
console.log(str.includes(“l”));
// false
console.log(str.includes(“x”);
You can also use indexOf()
to find if the string or char exists in the string. If exists, it returns index of character (if you use string (ex: “el”), then you will get the index of first character of the string). If not exists, then it returns -1. As you notice, indexOf()
can be used for finding the index of the character in the string.
Replace Character
let str = “hello world”;
// this will replace char ‘o’ to ‘l’
str.replace(“o”, “l”);
// this will remove empty space
str.replace(“ “, “”);
You may also want to replace the character with the specific index. Then create the following function using .substr()
.
const replaceAt = (index, str, rep) => {
return str.substr(0, index) + rep + str.substr(index + rep.length);
};
Remove Character
If you want to remove the specific character from the string, you can use replace()
method to remove all the matching characters. However, most of the time, you may want to remove the certain character with the specific index. In this case, you can use two different ways.
using substring
let str = “hello world”;
const removeChar = (str, index) => {
str.substring(0, index) + str.substring(index + 1);
};
// this will result “helo world”
console.log(removeChar(str, 3));
using slice
let str = “hello world”;
const removeChar = (str, index) => {
return str.slice(0, index) + str.slice(index + 1, str.length);
};
// this will result “helo world”
console.log(removeChar(str, 3));
String to Number
// 2
parseInt(“2”);
// 2.0
parseFloat(“2.0”);
String to Lower/Upper case
// he
str.toLowerCase(“HE”);
// HE
str.toUpperCase(“he”);
Convert into an array
Sometimes, to use an array functions, you may need to convert string into an array. To do this, you can use four options.
let str = “hello world”;
// [“h”, “e”, “l”, ”l”, “o”, “ “, “w”, “o”, “r”, “l”, “d”]
str.split(“”);
// [“hello”, “world”];
str.split(“ ”);
// [“h”, “e”, “l”, ”l”, “o”, “ “, “w”, “o”, “r”, “l”, “d”]
[…str];
// [“h”, “e”, “l”, ”l”, “o”, “ “, “w”, “o”, “r”, “l”, “d”]
Array.from(str);
// [“h”, “e”, “l”, ”l”, “o”, “ “, “w”, “o”, “r”, “l”, “d”]
Object.assign([], str);
Using loops to generate an array of Character from A to Z
const atoz = [];
// this will give A to Z (upper case alphabets)
for(let i =0; i < 26; i+=1) {
atoz.push(String.fromCharCode(65 + i));
}
// this will give a to z (lower case alphabets)
for(let i =0; i < 26; i+=1) {
atoz.push(String.fromCharCode(97 + i));
}
Top comments (0)