Skip to main content
Kinetic Community

Remove Spaces

On occasion the data which is either retrieved into a Service Item or entered into a service item contains leading or trailing white space or may even have more than one space between words.  This can cause problems with any logic that may use the values.  This is an example of javascript which can clean the extra spaces.

Resolution

To use this javascript copy the code below and insert it into your Service item.  Call the function with the appropriate parameter to execute it.

/**
* DESCRIPTION Removes leading and trailing white space and trims any multiple spaces in the middle to one space.
* @method trimSpace
* @param qstn {String} The question label of the question to remove spaces.
* @return value of the queston with white spaces removed
*/
function trimSpace(qstn) {
    // get value of the question adn place it into the variable qstn
    qstn = KD.utils.Action.getQuestionValue(qstn);
    
    // remove white space (tabs and line returns)
    qstn = qstn.replace(/\s+/g, " ");
    
    // remove multiple spaces
    qstn = qstn.replace(/[ ]{2,}/gi," ");
    
    // remove leading spaces
    qstn = qstn.replace(/^\s+/, '');
    
    // remove trailing spaces
    qstn = qstn.replace(/\s+$/, '');
    
    return qstn;
}