I want to take user input strings and add them together with proper spacing.
HTML:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<input id="input" type="text" placeholder="Words Go Here"></input>
<button id="addWords">Add Words</button>
<div id="output"></div>
</body>
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($('<span></span>').text(value + ' '));
} else {
alert('Please use characters only.');
}
}
})();
Example:
Is there a less-bulky (e.g. multiple if else
s) method for stripping away additional spaces?