w3resource

JavaScript: Create a new string from a given string taking the last 3 characters and added at both the front and back

JavaScript Basic: Exercise-26 with Solution

Write a JavaScript program to create a string from a given string. This is done by taking the last 3 characters and adding them at both the front and back. The string length must be 3 or more.

Pictorial Presentation:

JavaScript: Create a new string from a given string taking the last 3 characters and added at both the front and back

Sample Solution:

JavaScript Code:

// Define a function named front_back3 that takes a parameter str
function front_back3(str) {
  // Check if the length of str is greater than or equal to 3
  if (str.length >= 3) {
    // Set str_len to 3
    str_len = 3;
    // Extract the last three characters of str
    back = str.substring(str.length - 3);
    // Return the concatenation of back, str, and back
    return back + str + back;
  } else {
    // If the length of str is less than 3, return false
    return false;
  }
}

// Log the result of calling the front_back3 function with the argument "abc" to the console
console.log(front_back3("abc"));

// Log the result of calling the front_back3 function with the argument "ab" to the console
console.log(front_back3("ab"));

// Log the result of calling the front_back3 function with the argument "abcd" to the console
console.log(front_back3("abcd")); 

Sample Output:

abcabcabc
false
bcdabcdbcd

Live Demo:

See the Pen JavaScript: added characters added at both the front and back-basic- ex-25 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Create a new string from a given string taking the last 3 characters and added at both the front and back

ES6 Version:

// Using ES6 arrow function syntax to define the front_back3 function
const front_back3 = (str) => {
  // Check if the length of str is greater than or equal to 3
  if (str.length >= 3) {
    // Set str_len to 3
    const str_len = 3;
    // Extract the last three characters of str
    const back = str.substring(str.length - 3);
    // Return the concatenation of back, str, and back
    return back + str + back;
  } else {
    // If the length of str is less than 3, return false
    return false;
  }
};

// Log the result of calling the front_back3 function with the argument "abc" to the console
console.log(front_back3("abc"));

// Log the result of calling the front_back3 function with the argument "ab" to the console
console.log(front_back3("ab"));

// Log the result of calling the front_back3 function with the argument "abcd" to the console
console.log(front_back3("abcd"));

Previous: JavaScript program check if a given positive number is a multiple of 3 or a multiple of 7.
Next: JavaScript program to check if a string starts with 'Java' and false otherwise.

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.