function trimName(person) { // Check if the name of the person was defined // If not, return undefined if (person.name == 'undefined') { return 'undefined'; } else { // Otherwise trim the name and return it. return person.name.replace(/^\s+|\s+$/g, ''); } } // Create a person, set his name to " sam " with the spaces. var person = {}; person.name = " sam "; // Pass sam (the person object) to your function // Then alert() the result. alert(trimName(person));
Take a look at the code here and read the comments. We create a personβs object, set his name as the leading and final space. We pass it to a function where we test if it is defined. If so, we return the name cropped.
Further edited.
var person = {}; //creates the object "person" person.name = prompt('Please enter a name'); //defines name as a property function trimName(person) { //and gives it a value // If the property "name" is undefined // return undefined if (name === undefined) { //returns the code state "undefined" return undefined; // if name is undefined } else if (person.name === '') { //returns a prompt if no name is entered return 'Please enter a name'; } else { // Trim the "name" property, ensure it is a string return (person.name + '').trim(); //trims leading/trailing spaces } } trimName(person); //defines object person as a variable of function trimName
source share