Question:
Write a Javascript program to create a new string from a given string taking the first 3 characters and the last 3 characters of a string 'and adding them together. The string length must be 3 or more, if not, the original string is returned.
Answer:
function stringFormat (str) {
let str001 = str;
if (str001.length < 3) {
return str001;
} else {
let str002 = str001.slice(0, 3);
let str003 = str001.slice(-3);
let finalString = str002+str003;
console.log(finalString);
}
}
> we declare a function 'stringFormat'
> it has one parameter 'str'
> we create a variable str001 and initialize it with the argument 'str'
> we then open an if/else statement to check if the length of the 'str001' is less than 3
> if it is less than 3 then we want the function to return the 'str001' variable
> if it is 3 or more than 3 then we slice the str001 twice
>> our first slice is saved in variable 'str002' and slices the first 3 characters of the string
>> our second slice is saved in variable 'str003' and slices the last 3 characters of the string
> we then create another variable 'finalString'
> and initialize it with a value we get by concatenating the variables 'str002' and 'str003'
No comments:
Post a Comment