Regular Expression Spacer Replacer

[Total: 0    Average: 0/5]

This example replaces a pattern with another pattern.

Body Code:

Type all you want. After you type a new character the first textbox is copied into the second textbox and all occurances of spaces are replaced with  
<form name=f1>
<textarea onkeypress="setTimeout('showIt()',30)" name=t1 rows=10 cols=60>some spaces   are here    and there    </textarea>
<textarea name=t2  rows=10 cols=60></textarea>
</form>
<script>
function showIt()
{
var _f=document.f1;
var _t1=_f.t1.value;
var _regExp=/ss/gi;
/* this removes duplicate spaces */
while(_t1.match(_regExp)!=null) {
  _foundStr=_t1.match(_regExp)[0];
  _t1=_t1.replace(new RegExp(_foundStr,"gmi")," ");
 }
/* this replaces spaces with &nbsp; */
_regExp=/s/gi;
while(_t1.match(_regExp)!=null) {
  _foundStr=_t1.match(_regExp)[0];
  _t1=_t1.replace(new RegExp(_foundStr,"gmi"),"&nbsp;");
 }

_f.t2.value=_t1;
}
showIt();
</script>

<HR>
Now for another way to do the same thing:<BR>
(brought to us by Gavin Kistner)<BR>
<form name=f2>
<textarea onkeypress="setTimeout('showIt2()',30)" name=t3 rows=10 cols=60>some spaces   are here    and there    </textarea>
<textarea name=t4  rows=10 cols=60></textarea>
</form>
<script>
function showIt2()
{
  document.getElementById('t4').value=document.getElementById('t3').value.replace(/ss+/g,' ').replace(/s/g,'&nbsp;'); 
}
</script>

Times Viewed: 2

Leave a Reply

Your email address will not be published. Required fields are marked *