Question:
Write a Javascript program to create a new string adding 'New!' in front of a given string. If the given string begins with 'New!' already then return the original string.
Answer:
function newStr (str) {
let str001 = str;
if (str001.slice(0,4) === 'New!') {
return str001;
} else {
let str002 = 'New! ' + str001;
console.log(str002);
}
}
> we declare a function 'newStr'
> it has one parameter 'str'
> we declare a variable 'str001'
> we initialize it with a value of the argument 'str'
> we then use if / else statements to check if the string 'str001' begins with 'New!'
> we use the slice function to check if the string 'str001' begins with 'New!'
> we return the string 'str001' if it does
> if the string 'str001' it does not begin with 'New!' then we declare another variable 'str002'
> we initialize the value of the same by concatenating 'New! ' (with a space after the exclamation mark) with the original string variable 'str001'
> we then console.log 'str002'
No comments:
Post a Comment