w3resource

JavaScript: Convert a string in abbreviated form

JavaScript String: Exercise-5 with Solution

Write a JavaScript function to convert a string into abbreviated form.

Visual Presentation:

JavaScript: Convert a string in abbreviated form

Test Data :
console.log(abbrev_name("Robin Singh"));
"Robin S."

Sample Solution:

JavaScript Code:

 // Define a function named abbrev_name which takes a single parameter str1 representing a name string
abbrev_name = function (str1) {
    // Trim leading and trailing whitespace from the input string and split it into an array of substrings based on space (' ') delimiter
    var split_names = str1.trim().split(" ");
    // Check if the array contains more than one element (indicating both first name and last name are provided)
    if (split_names.length > 1) {
        // Return the abbreviation of the name in the format: first name followed by the first character of the last name and a period ('.')
        return (split_names[0] + " " + split_names[1].charAt(0) + ".");
    }
    // If only one name is provided, return the name as it is
    return split_names[0];
};
// Call the abbrev_name function with the input "Robin Singh" and log the result to the console
console.log(abbrev_name("Robin Singh"));

Output:

Robin S.

Explanation:

In the exercise above,

The code defines a function called "abbrev_name()" that takes a single parameter 'str1', which represents a name string. It trims any leading and trailing whitespace from the input string and splits it into an array of substrings based on the space (' ') delimiter.

If the array contains more than one element (indicating both a first name and a last name are provided), it returns an abbreviation of the name in the format: the first name followed by the first character of the last name and a period ('.'). If only one name is provided, it returns the name as it is.

Finally, it calls the "abbrev_name()" function with the input "Robin Singh" and logs the result to the console.

Flowchart:

Flowchart: JavaScript- Convert a string in  abbreviated form

Live Demo:

See the Pen JavaScript Convert a string in abbreviated form - string-ex-5 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to extract a specified number of characters from a string.
Next: Write a JavaScript function to hide email addresses to protect from unauthorized user.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-string-exercise-5.php