Richard Cornford wrote:
Eric Osman wrote:
I'm looking for a javascript function that will convert input such as
this:
<CLUB Code="
into this:
<CLUB Code="
<snip>
An example of such a function can be found at:-
<URL: http://www.crockford.com/javascript/remedial.html >
Richard.
THanks Richard,
The routines I wrote look like this:
//+-------------------------------------------------------------
//| quoteXml puts appropriate quoting around various elements so
//| that was interpretable xml (or html) code will now be
//| displayable.
//| A new string is returned.
//+-------------------------------------------------------------
function quoteXml (xmlStr) {
var result = new EditableString(xmlStr);
result = result.replaceAll("<", "<");
result = result.replaceAll(">", ">");
result = result.replaceAll("\"", """);
result = result.replaceAll("'", "'");
return result.data;
}
//+-------------------------------------------------------------
//| unquoteXml removes the quote marks, which is useful when
//| the returned stuff wants to be parsed as xml.
//+-------------------------------------------------------------
function unquoteXml (xmlStr) {
var result = new EditableString(xmlStr);
result = result.replaceAll("<", "<");
result = result.replaceAll(">", ">");
result = result.replaceAll(""", "\"");
result = result.replaceAll("'", "'");
return result.data;
}
Of course, to use them, you need my EditableString object definition too:
//+-------------------------------------------------------------
//| Object type editableString is a string that can be edited with
//| a number of useful methods contained below.
//+-------------------------------------------------------------
function EditableString(str) {
this.data = str;
}
//+-------------------------------------------------------------
//| replaceAll replaces all source strings with destination strings,
//| returning a new EditableString containing the result.
//+-------------------------------------------------------------
EditableString.prototype.replaceAll = function (srcStr, dstStr) {
this.pat = new RegExp(srcStr,"g");
var newStr = this.data.replace (this.pat, dstStr);
return new EditableString(newStr);
}
p.s. I often use an html "<textarea>" in which to display html that I
want to display for the person to see, so they angle brackets and
tags can all be seen.
However, I discovered that this is fine until you try to display
something like "&guot;" in a textarea. When you attempt that,
the browser (well, ie6 anyway) changes it back into a quote mark!
So, in order to make sure """ gets properly displayed, I
ended up having to change the ampersand to "&" , so for
example, if var requestBody has some stuff in it that I wasnt to
display in a textarea, and that stuff might have """ in it,
I further quote it like this:
new EditableString(requestBody).replaceAll("&","&" ).data)