[JS] Need help with Javascript...

Started by ShadowIce, April 14, 2011, 12:33:10 pm

Previous topic - Next topic

ShadowIce

how would I make it so that this code only replaces EACH = as I type them into the textarea with "\=" and NOT MORE THAN ONE \ ? new_text = new_text.replace("=","\\=");

it returns \\\=\\=\= instead of \=\=\=

Full code:

<script type="text/JavaScript">

function html2entities(sometext){
var re=/[(<>"'&]/g
arguments[i].value=sometext.replace(re, function(m){return replacechar(m)})
alert(arguments[i].value);
}

function replacechar(match){
if (match=="<")
 return "&lt;"
else if (match==">")
 return "&gt;"
else if (match=="\"")
 return "&quot;"
else if (match=="'")
 return "'"
else if (match=="&")
 return "&amp;"
}

//html2entities(document.forms.myform.textarea.value); //replace "<", ">", "&" and quotes in a form field with corresponding HTML entity instead

function generate(strValue)
{
  var newValue;

  newValue = replaceString(strValue, "<br>", "<br/>");
  newValue = replaceString(strValue, /\=/g, "\\=");
  document.forms[0].textarea.value = newValue;
}
function replaceString(inputStr,SearchPattern,ReplaceWith)
{
  return inputStr.replaceAll(SearchPattern,ReplaceWith);
}
</script>
<form name="form1" method="post" action="">
 <textarea name="textarea" onkeyUp="javascript:generate(document.forms.myform.textarea.value);"></textarea><br>
 <input type="button" name="Generate" value="Generate">
</form>

winkio

what is happening is:

you type '='
text is '='
it changes to '\='
you type another '='
text is '\=='
it changes to '\\=\='
you type another '='
text is '\\=\=='
it changes to '\\\=\\=\='

you should only be replacing new characters, not the entire text.

ShadowIce

An example would be nice please and thank you :)