1

Looking for pure JavaScript works specially in IE to remove all extra white-spaces from all inputs (text and textarea).

Here is the jQuery version that works but I want it in JavaScript:

function TrimText(el) {
 el.value = el.value.
 replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
 replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space
 replace(/\n +/, "\n"); // removes spaces after newlines
 return;
}

What is best approach to convert this to JavaScript?

$j(function () {
 $j("textarea").change(function () {
    TrimText(this);
 });

 $j("input").change(function () {
    TrimText(this);
 });
});

2 Answers 2

1

If you want to apply this to all inputs currently in the page:

document.querySelectorAll('input, textarea').forEach(function(el) {
  el.addEventListener('change', function(ev) { TrimText(ev.target); });
});

If you want to apply it to all inputs currently in the page, and all inputs created in the future:

document.addEventListener('change', function (ev) {
  if(ev.target.tagName === 'INPUT' || ev.target.tagName === 'TEXTAREA')
    TrimText(ev.target);
});

This works by using a mechanism called bubbling. Events in Javascript bubble up through the DOM and finally reaches the document element. So, we listen to the events in the document element and filter the events by the tag name of the target.

This is how JQuery works internally, and this approach is applicable to other things you can do in JQuery.

Sign up to request clarification or add additional context in comments.

Comments

0

Here's a simple JavaScript way as you asked. This removes every extra space, including leading and trailing spaces, and retains the single space.

Working demo:

function removeWhiteSpaces(){
    var value = document.getElementById("text").value;
    document.getElementById("text").value = value.replace(/\s+/g,' ').trim();
}
<input type="text" id="text" value="  I am  a bad    text"/>
<button onclick="removeWhiteSpaces()">Remove White Spaces</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.