JavaScript Interview Questions String

last two characters of a string,  remove all letters from a string,  remove all character from a string that appear more than one, find the number of occurrences of each character in a string, replace all occurrences of a string , reverse a string, split a string into segments of 3 characters from front, split a string into segments of 3 characters from back, show “\” in a string , create multi-line strings ,
             indexOf vs lastIndexOf, indexOf() vs search(), first letter of the string in an uppercase, capitalize first letter of each word ….

1. What is string in JavaScript?

A string is a sequence characters that may consist of letters, numbers, or symbols like “John Doe”. Strings in JavaScript are primitive data types and immutable, which means they are unchanging.

2 How do you check whether a string contains a substring?

There are 3 possible ways to check whether a string exists or not:

A) Using indexOf : You can use String.prototype.indexOf which returns the index of a substring if found otherwise return -1.

  

        var str1='If you think this has a happy ending, you haven’t been paying attention.';

        console.log(str1.indexOf('you'));  // output : 3
        console.log(str1.indexOf('we'));   // output : -1
    

B) Using includes : You can use String.prototype.includes which returns true if found otherwise return false.

  

        var str1='If you think this has a happy ending, you haven’t been paying attention.';
        console.log(str1.includes('you'));  // output: true
        console.log(str1.includes('we'));  // // output: false
    

C) Using regex : Using Regular expression's test method(RegExp.test), return true if test method passes otherwise false

  

        var regex =/you/;
        var regex1 =/we/;

        var str1='If you think this has a happy ending, you haven’t been paying attention.';
        console.log(regex.test(str1));   // output: true
        console.log(regex1.test(str1));  // output: false
    

3. how to get the last character of a string?

There are server ways to get the last character of a string and some of them are as follows:

A) Using bracket notation

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        var lastChar = str1[str1.length - 1];
        console.log(lastChar);  // output : n
    

B) charAt[index]

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        var lastChar =str1.charAt(str1.length -1);
        console.log(lastChar);  // output : n
    

C) substring

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        var lastChar =str1.substring(str1.length -1);
        console.log(lastChar);  // output : n
    

D) using slice

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        var lastChar =str1.slice(-1);
        console.log(lastChar);  // output : n
    

E) Using lambda expression

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';
        const getLastChar = (x) => x.split('').reverse().join(',').replace(',', '')[x.length === x.length + 1 ? 1 : 0];
        var result = getLastChar(str1)

        console.log(result);  // output : n
    

4. How to select last two characters of a string?

A) Using slice

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';
        var result= str1.slice(-2);

        console.log(result);  // output : on
    

B) Using substr()

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';
        var result =str1.substr(-2);

        console.log(result); // output : on
    

C) Using substrig()

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        var result = str1.substring(str1.length-2, str1.length)
        console.log(result); // output : on
    

5. How to remove all letters from a string in JavaScript?

  

        var str1 ='1234 Hello JavaScript 56789';

        let regex = /[a-z]/gi;

        var result = str1.replace(regex, '');

        console.log(result);  // output : 1234   56789

    

6. How to remove all character from a string that appear more than one?

For example : input : abcab , output : c

  

        function removeDuplicateChar(str) {
        var retVal = '';
        if (str && str.length > 0) {
        //
        for (let index = 0; index < str.length; index++) {

        // if first and and last index are same then there is no duplicate charter
        if (str.indexOf(str[index]) == str.lastIndexOf(str[index])) {
        retVal += str[index];
        }
        }
        }
        return retVal;
        }

        console.log(removeDuplicateChar('abcab'));  // Output : c
        console.log(removeDuplicateChar('123412')); // output : 34
    

7.how to find the number of occurrences of each character in a string?

A) Using loop

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        function chartCount(str) {
        let retVal = {};
        for(let i = 0; i < str.length; i++) {
        const currentLetter = str.charAt(i);
        retVal[currentLetter] = retVal[currentLetter] + 1 || 1;
        }
        return retVal;
        }

        var result =chartCount(str1);

        console.log(result);
    

B) Using reduce

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';
        function chartCountUsingReduce(str) {
        return str.split("").reduce((a, letter) => {
        a[letter] = (a[letter] || 0) + 1;
        return a;
        }, {});
        }

        var result1 =chartCountUsingReduce(str1);

        console.log(result1);
    

8. How do you replace all occurrences of a string in JavaScript?

You can use string replace method to replace the all the occurrences in string.
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

A) Using searchValue and newValue

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        var result = str1.replace('this','that');
        console.log(result);

    

B) Using Regex

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';
        var regex=/this/g;

        var result1 = str1.replace(regex,'that')

        console.log(result1);
    

C) Using Split

  

        attention';

        var result2 = str1.split('this').join('that');

        console.log(result2);
    

9. How do you reverse a string in JavaScript?

A) using split

  

        var str1='John Doe'

        str1 = str1.split(""); //convert the string to array
        str1 = str1.reverse(); // revers the array
        str1 = str1.join(""); //then join the reverse order values together
        console.log(str1);  // output : eoD nhoJ
    

B) using for loop increment

  

        function reverseStringUsingLoopIncrement(str){
        let retVal ="";
        for(let i= 0; i<str.length; i++){
                                    retVal=str[i]+retVal;
                                    }
                                    return retVal;
                                    }
                                    var str1='John Doe'
                                    var result=reverseStringUsingLoopIncrement(str1)
                                    console.log(result);
    

C) using for loop decrement

  

        function reverseStringUsingLoopDecrement(str){
        let retVal = "";
        for(let i = str.length-1; i>=0; i--){
        retVal = retVal+ str[i];
        }
        return retVal;
        }

        var str1='John Doe'
        var result = reverseStringUsingLoopDecrement(str1)
        console.log(result);
    

D) Using for-of loop

  

        function reverseStringUsingForOfLoop(str){
        let retval ="";
        for(let char of str){
        retval = char + retval;
        }
        return retval;
        }
        var str1='John Doe'
        var result = reverseStringUsingForOfLoop(str1)
        console.log(result); // output :  eoD nhoJ
    

E) Using foreach loop

  

        function reverseStringUsingForeachLoop(str){
        let retVal = "";
        str.split("").forEach(function(char){
        retVal = char + retVal;
        });
        return retVal;
        }

        var str1='John Doe'
        var result = reverseStringUsingForeachLoop(str1)
        console.log(result); // output :  eoD nhoJ

    

F) using ES6

  

        function reverseStringUsingES6(str) {
        let retVal = "";
        str.split("").forEach(ch => retVal = ch + retVal);
        return retVal;
        }

        var str1 = 'John Doe'
        var result = reverseStringUsingES6(str1)
        console.log(result); // output :  eoD nhoJ

    

E) using reduce

  

        function reverseStringUsingReduce(str) {
        return str.split("").reduce(function (retVal, char) {
        return char + retVal;
        }, "");
        }

        var str1 = 'John Doe'
        var result = reverseStringUsingReduce(str1)
        console.log(result); // output :  eoD nhoJ
    

F) Using Recursion

  

        function reverseStringUsingRecursion(str){
        return str ? reverseStringUsingRecursion(str.substr(1)) + str[0] : str;
        };

        var str1 = 'John Doe'
        var result = reverseStringUsingRecursion(str1)
        console.log(result); // output :  eoD nhoJ

    

10. How can I split a string into segments of 3 characters?

A) Using regex

  

        var str = 'abcdefghijklm';
        console.log(str.match(/.{1,3}/g));  // output : [ 'abc', 'def', 'ghi', 'jkl', 'm' ]

    

B) using for loop

  

        function splitStringIntoSegmentOfN(str, n) {
        var retVal = []
        for (var i = 0, charsLength = str.length; i < charsLength; i += n) {
        retVal.push(str.substring(i, i + n));
        }
        return retVal;
        }

        var str = 'abcdefghijklm';
        var result = splitStringIntoSegmentOfN(str, 3);
        console.log(result);  // output : [ 'abc', 'def', 'ghi', 'jkl', 'm' ]

    

C) Using while loop

  

        function splitStringIntoSegmentOfNUsingWhile(str, n) {

        let retVal = [], remaining = str;

        while (remaining) {
        let v = remaining.slice(0, n);
        remaining = remaining.slice(v.length);
        retVal.push(v);
        }

        return retVal;

        };

        var str = 'abcdefghijklm';
        var result1 = splitStringIntoSegmentOfNUsingWhile(str, 3);
        console.log(result1); // output : [ 'abc', 'def', 'ghi', 'jkl', 'm' ]
    

D) Using ES6

  

        function splitStringIntoSegmentOfNUsingES6(str, n) {
        const retVal = [];
        for (
        const array = Array.from(str);
        array.length;
        retVal.push(array.splice(0,n).join('')));
        return retVal;
        }

        var str = 'abcdefghijklm';
        var result1 = splitStringIntoSegmentOfNUsingES6(str, 3);
        console.log(result1); // output : [ 'abc', 'def', 'ghi', 'jkl', 'm' ]
    

11. How can I split a string into segments of 3 characters from back/end?

A) using for loop

  

        function splitStringIntoSegmentFromEndUsingLoop(str, n) {
        var i = str.length % n;
        var retVal = i ? [str.substr(0, i)] : [];
        for (; i < str.length; i += n) {
        retVal.push(str.substr(i, n));
        }
        return retVal;
        }

        var str = 'abcdefghijklm';
        var result1 = splitStringIntoSegmentFromEndUsingLoop(str, 3);
        console.log(result1); // output : [ 'a', 'bcd', 'efg', 'hij', 'klm' ]
    

B) using slice

  

        function splitStringIntoSegmentFromEndUsingSlice(str, n) {
        var retVal = [];
        var len = str.length;
        while (len > 0) {
        len -= n;
        retVal.unshift(str.slice(len));
        str = str.slice(0, len);
        }
        return retVal;
        }

        var str = 'abcdefghijklm';
        var result1 = splitStringIntoSegmentFromEndUsingSlice(str, 3);
        console.log(result1); // output : [ 'a', 'bcd', 'efg', 'hij', 'klm' ]
    

C) using Regex

  

        var str = 'abcdefghijklm';
        var result1= str.split( /(?=(?:...)*$)/ )
        console.log(result1); // output : [ 'a', 'bcd', 'efg', 'hij', 'klm' ]

    

12. How do you show “\” in a string in JavaScript?

You can use \\ to show the \ escape character.

  


        var x = "John \\ Doe";
        console.log(x);  // output  : John \ Doe

        var x = 'John \\ Doe';
        console.log(x); // output  : John \ Doe

    

13. How do you create multi-line strings in JavaScript?

JavaScript could be created using the newline escape character \n. This is a functionality that JavaScript inherited from the C programming language.

  


        var str1='If you think \n this has a happy ending, \n you haven’t been \n paying attention';
        console.log(str1);
        // output
        If you think
        this has a happy ending,
        you haven’t been
        paying attention

    

14. What is the difference between indexOf and lastIndexOf in JavaScript?

indexOf() method returns the position of the first occurrence of a specified value in a string.

lastIndexOf() method returns the position of the last occurrence of a specified value in a string.

  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        console.log(str1.indexOf('you')); // output : 3

        console.log(str1.lastIndexOf('you')); // output : 38

    

15. What is the difference between indexOf() and search()?

 search() :

  • value can be search using regex as well.
  • Cannot have start position argument.

indexOf() :

  • Cannot take regex for search
  • Can take start position as a second argument
  

        var str1='If you think this has a happy ending, you haven’t been paying attention';

        console.log(str1.search('you')); // output : 3
        var regex =/you/;
        console.log(str1.search(regex)); // output : 3

        console.log(str1.indexOf('you',10)); // output : 38
    

16. What is the difference between string primitives and String objects in JavaScript?

string : String are immutable, which means, once they are created, their state can't be changed, which also makes them thread safe. String is the JavaScript String type, which you could use to create new strings.

  

        var a = 'jd';
        var b = 'jd';
        console.log(a ==b);  // true

    

a==b result will be 'true' both string reefer’s same object.

String It is parsed to a v8:StringObject (https://v8docs.nodesource.com/node-0.8/d9/d38/classv8_1_1_string_object.html )which extends Object and, apart from being a full-fledged object, serves as a wrapper for v8::String.

  


        var x = new String("jd");
        var y = new String("jd");

        console.log(x ==y);  //false
    

a==b result will be false, because they have different references.

17. How do you make first letter of the string in an uppercase?

You can make the first letter to uppercase using different ways and some of them are as follows :

A) using toUpperCase and Slice

  

        var str1='if you think this has a happy ending, you haven’t been paying attention';

        function uppercaseFirstLetter1(string) {
        return string[0].toUpperCase() + string.slice(1);
        }
        console.log(uppercaseFirstLetter1(str1));
    

B) using chartAt, toUpperCase and Slice

  

        var str1='if you think this has a happy ending, you haven’t been paying attention';
        function uppercaseFirstLetter2(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
        }
        console.log(uppercaseFirstLetter2(str1));
    

C) using regex

  

        var str1='if you think this has a happy ending, you haven’t been paying attention';

        function uppercaseFirstLetter3(string) {
        return string.replace(/^./, string[0].toUpperCase());
        }
        console.log(uppercaseFirstLetter3(str1));
    

D) using prototype

  

        var str1='if you think this has a happy ending, you haven’t been paying attention';

        String.prototype.uppercaseFirstLetter4 = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
        }

        console.log(str1.uppercaseFirstLetter4());
    

E) using ES6 template string

  


        var str1='if you think this has a happy ending, you haven’t been paying attention';
        str1 =  `${str1[0].toUpperCase()}${str1.slice(1)}`;
        console.log(str1);

    

F) using ES6

  

        var str1='if you think this has a happy ending, you haven’t been paying attention';

        var result = str1.replace(/^./, str => str.toUpperCase())
        console.log(result);
    

18. How to capitalize first letter of each word in JavaScript?

A) Using split, map and join

  

        function toTitleCase(str) {
        return str
        .toLowerCase()
        .split(' ')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ');
        };


        var str1='if you think this has a happy ending, you haven’t been paying attention';

        var result = toTitleCase(str1);
        console.log(result);  // output: If You Think This Has A Happy Ending, You Haven’t Been Paying Attention
    

B) Using for loop

  

        function toTitleCase1(str) {

        var retVal = str.toLowerCase().split(' ');
        for (var i = 0; i < retVal.length; i++) {
        var subString = retVal[i].split('');
        for (var j = 0; j < subString.length; j++) {
        subString[0] = subString[0].toUpperCase();

        }
        retVal[i] = subString.join('');
        }
        return retVal.join(' ');
        }

        var str1='if you think this has a happy ending, you haven’t been paying attention';

        var result = toTitleCase1(str1);
        console.log(result);  // output: If You Think This Has A Happy Ending, You Haven’t Been Paying Attention
    

C) Using regex

  

        function toTitleCase2(str) {
        return str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());

        }


        var str1='if you think this has a happy ending, you haven’t been paying attention';

        var result = toTitleCase2(str1);
        console.log(result);  // output: If You Think This Has A Happy Ending, You Haven’t Been Paying Attention
    

D) Using foreach

  

        function toTitleCase3(str) {
        var tempArray = str.trim().toLowerCase().split(' ');
        var retVal = [];
        tempArray.forEach(function(elem, i) {
        retVal.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
        });
        return retVal.join(' ');
        }

        var str1='if you think this has a happy ending, you haven’t been paying attention';

        var result = toTitleCase3(str1);
        console.log(result);  // output: If You Think This Has A Happy Ending, You Haven’t Been Paying Attention


    

19. How do you check if a string starts with specified/given string?

You can use String.prototype.startsWith() method to check a string starts with specified string or not. If string start with specified string, then return true otherwise return false.

  

        var str1 ='John Doe'

        console.log(str1.startsWith('John'));  // output : true
        console.log(str1.startsWith('Doe'));   // output : false

    

20. How do you check if a string end with specified/given string?

You can use String.prototype.endsWith() method to check a string end with specified string or not. If string end with specified string, then return true otherwise return false.

  

        var str1 ='John Doe'
        console.log(str1.endsWith('John'));  // output : false
        console.log(str1.endsWith('Doe'));   // output : true