Hi everyone!
I have a task where I need to make an abbreviation out of a name that is called in a function.
Sorry if it difficult to understand, but the task is following:
Occasionally, one wants to use initials for parts of a name, rather than the full name. For example, the name “Chester Desmond” could be abbreviated to “C. Desmond” (note the initial and the full stop). In the text from Exercise 7 we would have to do so three times, and with even longer texts, it is desirable to have it done automatically, rather than doing it manually.
Hence, you must now write a function that abbreviates names automatically. Declare a function that has as its only argument a string and returns the text where the first three occurrences of “Chester Desmond” have been replaced by “C. Desmond”.
First think about the solution and then write it down in everyday language! Then program it.
Hint: Recall that you can use […] to find the symbol at an index in a string; and that you can use .indexOf() to find the index of a symbol or string in another string; that you can use .slice() to extract substrings of a string; and that you can use .length to find the length of a string.
Test your function by performing calls of it.
I’ve tried to make this function:
function abbreviate_name(name) {
var Chester = name.indexOf(‘Chester Desmond’)
var Chester2 = name[Chester];
var abbreviation = Chester2 + ‘.’
return abbreviation;
};
abbreviate_name(‘Chester Desmond’);
If I call the function it gives med ‘C.’ which is correct, but I am lost in how to do the Desmond part.
Anyone who can help?
Best Regards
Frederik