HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Removing extra spaces from user input

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
removinguserspacesinputfromextra

Problem

I want to take user input strings and add them together with proper spacing.

HTML:


Add Words


JavaScript:

(function () {

 $('#addWords').on('click', addWords);

 function addWords() {

    var value = $('#input').val();
    var firstChar = value.charAt(0);
    var lastChar = value.slice(-1);

     if ((/^[a-zA-Z\s]*$/.test(value)) && (value !== '')) {

         if (firstChar == ' ' && lastChar == ' ') {

            value = value.trimLeft().trimRight();

         } else if (firstChar == ' ') {

            value = value.trimLeft();

         } else if (lastChar == ' ') {

            value = value.trimRight();

         } else {

            value = value;
        }

        $('#output').append($('').text(value + ' '));

     } else {

        alert('Please use characters only.');

     }
 }

})();


Example:

JSFiddle

Is there a less-bulky (e.g. multiple if elses) method for stripping away additional spaces?

Solution

If I'm not misunderstanding the intent of your script you don't need the if elses at all.

For starters not having a space to trim when calling trim(Right or Left) is not a problem. No errors are thrown. So you could just do this:

function addWords() {
    var value = $('#input').val();

    if ((/^[a-zA-Z\s]*$/.test(value)) && (value !== '')) {
        value = value.trimLeft().trimRight();
        $('#output').append($('').text(value + ' '));
    } else {
        alert('Please use characters only.');
    }
}


For simplicities sake instead of value.trimLeft().trimRight() you can just use value.trim().

Edit: Also as Dagg pointed out(see comments below) String.prototype.trimLeft() and String.prototype.trimRight() are non-standard but String.prototype.trim() is in the spec's for ES5.

Code Snippets

function addWords() {
    var value = $('#input').val();

    if ((/^[a-zA-Z\s]*$/.test(value)) && (value !== '')) {
        value = value.trimLeft().trimRight();
        $('#output').append($('<span></span>').text(value + ' '));
    } else {
        alert('Please use characters only.');
    }
}

Context

StackExchange Code Review Q#53934, answer score: 4

Revisions (0)

No revisions yet.