JavaScript: Check whether a string "Script" presents at 5th (index 4) position in a given string
JavaScript Basic: Exercise-30 with Solution
Write a JavaScript program to check whether a string "Script" appears at the 5th (index 4) position in a given string. If "Script" appears in the string, return the string without "Script" otherwise return the original one.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named check_script that takes a string parameter str
function check_script(str) {
// Check if the length of the string is less than 6
if (str.length < 6) {
// If true, return the original string as it is
return str;
}
// Initialize a variable result_str with the value of the input string
let result_str = str;
// Check if the substring from index 10 to index 4 (exclusive) is equal to 'Script'
if (str.substring(10, 4) == 'Script') {
// If true, update result_str to exclude the substring 'Script' from index 4 to the end
result_str = str.substring(0, 4) + str.substring(10, str.length);
}
// Return the final result_str
return result_str;
}
// Log the result of calling check_script with the argument "JavaScript" to the console
console.log(check_script("JavaScript"));
// Log the result of calling check_script with the argument "CoffeeScript" to the console
console.log(check_script("CoffeeScript"));
Output:
Java CoffeeScript
Live Demo:
See the Pen JavaScript: check if a string Script presents at 5th position - ex-30 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Define a function named check_script that takes a string parameter str
const check_script = (str) => {
// Check if the length of the string is less than 6
if (str.length < 6) {
// If true, return the original string as it is
return str;
}
// Initialize a variable result_str with the value of the input string
let result_str = str;
// Check if the substring from index 10 to index 4 (exclusive) is equal to 'Script'
if (str.substring(10, 4) == 'Script') {
// If true, update result_str to exclude the substring 'Script' from index 4 to the end
result_str = str.substring(0, 4) + str.substring(10, str.length);
}
// Return the final result_str
return result_str;
};
// Log the result of calling check_script with the argument "JavaScript" to the console
console.log(check_script("JavaScript"));
// Log the result of calling check_script with the argument "CoffeeScript" to the console
console.log(check_script("CoffeeScript"));
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to check if three given integer values are in the range 50..99.
Next: JavaScript program to find the largest of three given integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics