-1

In JavaScript/jQuery, what is the best/fastest way to transform two or more spaces in only one space in any string of an input field?

Possibly without regex, please.

<script>
function spaces() {
   var textInput = insertText.value;
   while (textInput.includes("  ")) {
     var textInput = (textInput.replace("  ", " "));
    }
   alert(textInput);
}
</script>
<input type="text" id="insertText" value="word1    word2">
<button onclick="spaces()">ok</button>
Juri
  • 311
  • 4
  • 12
  • 2
    *"Possibly without regex, please.'* Why? That kind of arbitrary restriction *must* be accompanied with a reason for it. Regex is exactly how you do this. – T.J. Crowder Jan 29 '17 at 15:03
  • 1
    This is one of those cases where I **know** there are many duplicates, but the SO search mechanism is just not up to the task of finding them. – Pointy Jan 29 '17 at 15:10
  • 2
    Possible duplicate of [Replace multiple whitespaces with single whitespace in JavaScript string](http://stackoverflow.com/questions/6163169/replace-multiple-whitespaces-with-single-whitespace-in-javascript-string) - There are also solutions without regular expressions. – GOTO 0 Jan 29 '17 at 15:23
  • 1
    I'm not sure if this is OP's reasoning, but when I started JavaScript, I didn't like to use regular expressions because they look terrible, make no sense to the uninitiated, and are never explained by the initiated (answers to this question and almost every other one on SO are a good example of this). I really only learnt regular expression syntax when I found [Regex101](https://regex101.com/), which explains regex syntax and I would recommend to the OP to make sense of these answers. – James Hay Jan 29 '17 at 15:32

2 Answers2

1

Use a regular expression as the first parameter of replace. /\s{2,}/g will do.

<script>
function spaces() {
   var textInput = insertText.value;
   // no need for a loop here
   var textInput = textInput.replace(/\s{2,}/g, " ");

   alert(textInput);
}
</script>
<input type="text" id="insertText" value="word1    word2">
<button onclick="spaces()">ok</button>
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

You could use a regular expression and search for white space.

function spaces() {
   insertText.value = insertText.value.replace(/\s+/g, " ");
}
<input type="text" id="insertText" value="word1    word2">
<button onclick="spaces()">ok</button>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392