Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all strings "<" and ">" in a variable with "&lt;" and "&gt;"

I am currently trying to code an input form where you can type and format a text for later use as XML entries. In order to make the HTML code XML-readable, I have to replace the code brackets with the corresponding symbol codes, i.e. < with &lt; and > with &gt;.

The formatted text gets transferred as HTML code with the variable inputtext, so we have for example the text

The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.

which needs to get converted into

The &lt;b&gt;Genji&lt;/b&gt; and the &lt;b&gt;Heike&lt;/b&gt; waged a long and bloody war.

I tried it with the .replace() function:

inputxml = inputxml.replace("<", "&lt;");       
inputxml = inputxml.replace(">", "&gt;");

But this would just replace the first occurrence of the brackets. I'm pretty sure I need some sort of loop for this; I also tried using the each() function from jQuery (a friend recommended I looked at the jQuery package), but I'm still new to coding in general and I have troubles getting this to work.

How would you code a loop which would replace the code brackets within a variable as described above?

Additional information

You are, of course, right in the assumption that this is part of something larger. I am a graduate student in Japanese studies and currently, I am trying to visualize information about Japenese history in a more accessible way. For this, I am using the Simile Timeline API developed by MIT grad students. You can see a working test of a timeline on my homepage.

The Simile Timeline uses an API based on AJAX and Javascript. If you don't want to install the AJAX engine on your own server, you can implement the timeline API from the MIT. The data for the timeline is usually provided either by one or several XML files or JSON files. In my case, I use XML files; you can have a look at the XML structure in this example.

Within the timeline, there are so-called "events" on which you can click in order to reveal additional information within an info bubble popup. The text within those info bubbles originates from the XML source file. Now, if you want to do some HTML formatting within the info bubbles, you cannot use code bracket because those will just be displayed as plain text. It works if you use the symbol codes instead of the plain brackets, however.

The content for the timeline will be written by people absolutely and totally not accustomed to codified markup, i.e. historians, art historians, sociologists, among them several persons of age 50 and older. I have tried to explain to them how they have to format the XML file if they want to create a timeline, but they occasionally slip up and get frustrated when the timeline doesn't load because they forgot to close a bracket or to include an apostrophe.

In order to make it easier, I have tried making an easy-to-use input form where you can enter all the information and format the text WYSIWYG style and then have it converted into XML code which you just have to copy and paste into the XML source file. Most of it works, though I am still struggling with the conversion of the text markup in the main text field.

The conversion of the code brackets into symbol code is the last thing I needed to get working in order to have a working input form.

like image 324
Michael Avatar asked May 23 '11 07:05

Michael


People also ask

How do you replace and in a string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you replace all occurrences?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')

Does string replace replacing all occurrences?

Java String replace() method replaces every occurrence of a given character with a new character and returns a new string.


2 Answers

look here:

http://www.bradino.com/javascript/string-replace/

just use this regex to replace all:

str = str.replace(/\</g,"&lt;")   //for <
str = str.replace(/\>/g,"&gt;")   //for >
like image 68
Fender Avatar answered Oct 02 '22 13:10

Fender


To store an arbitrary string in XML, use the native XML capabilities of the browser. It will be a hell of a lot simpler that way, plus you will never have to think about the edge cases again (for example attribute values that contain quotes or pointy brackets).

A tip to think of when working with XML: Do never ever ever build XML from strings by concatenation if there is any way to avoid it. You will get yourself into trouble that way. There are APIs to handle XML, use them.

Going from your code, I would suggest the following:

$(function() {

  $("#addbutton").click(function() {
    var eventXml = XmlCreate("<event/>");
    var $event   = $(eventXml);

    $event.attr("title", $("#titlefield").val());
    $event.attr("start", [$("#bmonth").val(), $("#bday").val(), $("#byear").val()].join(" "));

    if (parseInt($("#eyear").val()) > 0) {
      $event.attr("end", [$("#emonth").val(), $("#eday").val(), $("#eyear").val()].join(" "));
      $event.attr("isDuration", "true");
    } else {
      $event.attr("isDuration", "false");
    }

    $event.text( tinyMCE.activeEditor.getContent() );

    $("#outputtext").val( XmlSerialize(eventXml) );
  });

});

// helper function to create an XML DOM Document
function XmlCreate(xmlString) {
  var x;
  if (typeof DOMParser === "function") {
    var p = new DOMParser();
    x = p.parseFromString(xmlString,"text/xml");
  } else {
    x = new ActiveXObject("Microsoft.XMLDOM");
    x.async = false;
    x.loadXML(xmlString);
  }
  return x.documentElement;
}

// helper function to turn an XML DOM Document into a string
function XmlSerialize(xml) {
  var s;
  if (typeof XMLSerializer === "function") {
    var x = new XMLSerializer();
    s = x.serializeToString(xml);
  } else {
    s = xml.xml;
  }
  return s
}
like image 34
Tomalak Avatar answered Oct 02 '22 13:10

Tomalak