cleanSpaces - JSFiddle - JSFiddle

by toubia95

HTML

<div>
  <textarea id="area1"></textarea>
</div>
<br>
<a href="#" id="convertir">cleanMultiSpaces »</a>
<br>
<br>
<div>
  <textarea id="area2"></textarea>
</div>
<br>

CSS

/*
<p>1 2  3   4    5     6      7       8        9         0<p>
*/


/*
sdfgsdf gsfg . s dfhgs df h . sdfg s dfh . sdf
 ghjkfgh . fghjfghjfgh . fghjfghjfghj . fghjfghj . fghjfghj f
*/

body {
  text-align: center;
}

textarea {
  width: 95%;
  height: 150px;
}

#convertir {
  margin: 100 0;
}

JavaScript

// https://regexr.com/

$("#convertir").click(function() {
	alert("toto1");
  $("#area2").val('');
  var myHtml = $("#area1").val();
  if (myHtml.match(/  /)) { //if (/  /.test(myHtml)) {
    // remplacer les espaces mutiples
    myHtml = myHtml.replace(/ +/g, " "); // PURE REGEX
  } else {
    alert("toto2");
    myHtml = "Rien à remplacer !";
  }

  /*
 var str = "coucou monde !";
var résultat = /^coucou/.test(str);
console.log(résultat); // true
*/

  // ajouter 5 espaces au début de la sélection
  //myHtml = myHtml.replace(/^/g,"     ");
  //myHtml = myHtml.replace(/\n/g,"\n     ");
  //myHtml = myHtml.replace(/(^|(\n))/g,"\2     ");

  $("#area2").val(myHtml);
});

/*
// RECURSIVE FUNCTION
var remSpaces = function(str) {
  if (str.match(/\s\s/g)) {
    str = str.replace(/\s\s/g, ' ');
    return remSpaces(str);
  } else {
    return str;
  }
};

$("#convertir").click(function() {
  $("#area2").val('');
  var myHtml = $("#area1").val();

  myHtml = remSpaces(myHtml);

  $("#area2").val(myHtml);
});
*/