w3resource

JavaScript: Create a new string of 4 copies of the last 3 characters of a given original string

JavaScript Basic: Exercise-58 with Solution

Write a JavaScript program to create an updated string of 4 copies of the last 3 characters of a given original string. The string length must be 3 and above.

Pictorial Presentation:

JavaScript: Create a new string of 4 copies of the last 3 characters of a given original string

Sample Solution:

JavaScript Code:

// Define a function named newstring with parameter str
function newstring(str) {
    // Check if the length of str is greater than or equal to 3
    if (str.length >= 3) {
        // Extract the last 3 characters of str
        result_str = str.substring(str.length - 3);
        // Return a new string containing the last 3 characters repeated four times
        return result_str + result_str + result_str + result_str;
    } else {
        // Return false if the length of str is less than 3
        return false;
    }
}

// Call the function with sample arguments and log the results to the console
console.log(newstring("Python 3.0"));
console.log(newstring("JS"));
console.log(newstring("JavaScript")); 

Sample Output:

3.03.03.03.0
false
iptiptiptipt

Live Demo:

See the Pen JavaScript - Create a new string of 4 copies of the last 3 characters of a string - basic-ex-57 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Create a new string of 4 copies of the last 3 characters of a given original string

ES6 Version:

// Define a function named newstring with parameter str
const newstring = (str) => {
    // Check if the length of the string is greater than or equal to 3
    if (str.length >= 3) {
        // Use template literals to repeat the last three characters of the string
        return `${str.slice(-3)}${str.slice(-3)}${str.slice(-3)}${str.slice(-3)}`;
    } else {
        // Return false if the length is less than 3
        return false;
    }
};

// Call the function with sample arguments and log the results to the console
console.log(newstring("Python 3.0"));
console.log(newstring("JS"));
console.log(newstring("JavaScript"));

Previous: JavaScript program to create a new string of specified copies (positive number) of a given string.
Next: JavaScript program to extract the first half of a string of even length.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.