Javascript 将变量中的所有字符串“<”和“>”替换为“<” 和“>”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6093986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:12:09  来源:igfitidea点击:

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

javascriptjquerystringloopsreplace

提问by Michael

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;.

我目前正在尝试编写一个输入表单,您可以在其中键入和格式化文本以供以后用作 XML 条目。为了使HTML代码XML可读,我有与相应的符号代码,即,替换码括号<&lt;>&gt;

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

格式化的文本作为带有变量inputtext 的HTML 代码传输,因此我们有例如文本

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:

我用 .replace() 函数试了一下:

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.

但这只会替换第一次出现的括号。我很确定我需要某种循环;我还尝试使用each()jQuery 中的函数(一位朋友建议我查看 jQuery 包),但我对一般的编码仍然很陌生,而且我在让它工作时遇到了麻烦。

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.

当然,您认为这是更大事物的一部分是正确的。我是日本研究的研究生,目前,我正在尝试以一种更容易理解的方式可视化有关日本历史的信息。为此,我使用了麻省理工学院研究生开发的 Simile Timeline API。你可以在我的主页上看到一个时间线的工作测试。

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.

Simile Timeline 使用基于 AJAX 和 Javascript 的 API。如果不想在自己的服务器上安装 AJAX 引擎,可以从 MIT 实现时间轴 API。时间线的数据通常由一个或多个 XML 文件或 JSON 文件提供。就我而言,我使用 XML 文件;您可以查看此示例中的 XML 结构。

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.

在时间线中,您可以单击所谓的“事件”,以便在信息气泡弹出窗口中显示其他信息。这些信息气泡中的文本源自 XML 源文件。现在,如果您想在信息气泡中进行一些 HTML 格式设置,则不能使用代码括号,因为它们只会显示为纯文本。但是,如果您使用符号代码而不是普通括号,它会起作用。

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.

时间线的内容将由绝对和完全不习惯编码标记的人编写,即历史学家、艺术史学家、社会学家,其中有几个 50 岁及以上的人。我试图向他们解释,如果他们想创建时间线,他们必须如何格式化 XML 文件,但是当时间线未加载时,他们偶尔会滑倒并感到沮丧,因为他们忘记关闭括号或包含撇号.

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.

为了使它更容易,我尝试制作一个易于使用的输入表单,您可以在其中输入所有信息并格式化文本 WYSIWYG 样式,然后将其转换为 XML 代码,您只需将其复制并粘贴到XML 源文件。大多数都有效,但我仍在努力转换主文本字段中的文本标记。

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.

将代码括号转换为符号代码是我获得工作输入表单所需的最后一件事。

采纳答案by Tomalak

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).

要在 XML 中存储任意字符串,请使用浏览器的本机 XML 功能。这样会简单得多,而且您将永远不必再次考虑边缘情况(例如,包含引号或尖括号的属性值)。

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 willget yourself into trouble that way. There are APIs to handle XML, use them.

使用 XML 时要考虑的一个技巧:如果有任何方法可以避免的话,永远不要通过串联从字符串构建 XML。这样你就会陷入困境。有处理 XML 的 API,请使用它们。

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
}

回答by Fender

look here:

看这里:

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

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 >

回答by katspaugh

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

You might use a regular expression with the "g" (global match) flag.

您可以使用带有“g”(全局匹配)标志的正则表达式。

var entities = {'<': '&lt;', '>': '&gt;'};

'<inputtext><anotherinputext>'.replace(
    /[<>]/g, function (s) {
        return entities[s];
    }
);

回答by Theofanis Pantelides

You could also surround your XML entries with the following:

您还可以使用以下内容包围您的 XML 条目:

<![CDATA[...]]>

See example:

见示例:

<xml>
  <tag><![CDATA[The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.]]></tag>
</xml>

Wikipedia Article: http://en.wikipedia.org/wiki/CDATA

维基百科文章:http: //en.wikipedia.org/wiki/CDATA

回答by Félix Saparelli

What you really need, as mentioned in comments, is to XML-encode the string. If you absolutely want to do this is Javascript, have a look at the PHP.js function htmlentities.

正如评论中提到的,您真正需要的是对字符串进行 XML 编码。如果您绝对想使用 Javascript,请查看 PHP.js 函数htmlentities

回答by Ravi Ram

I created a simple JS function to replace Greater Than and Less Than characters

我创建了一个简单的 JS 函数来替换大于和小于字符

Here is an example dirty string: <[email protected]>

这是一个脏字符串示例: < [email protected] >

Here is an example cleaned string: [ [email protected] ]

下面是一个清理过的字符串示例: [[email protected]]

function RemoveGLthanChar(notes) {
    var regex = /<[^>](.*?)>/g;
    var strBlocks = notes.match(regex);

    strBlocks.forEach(function (dirtyBlock) {
        let cleanBlock = dirtyBlock.replace("<", "[").replace(">", "]");
        notes = notes.replace(dirtyBlock, cleanBlock);
    });

    return notes;
}

Call it using

调用它使用

$('#form1').submit(function (e) {
    e.preventDefault();
    var dirtyBlock = $("#comments").val();
    var cleanedBlock = RemoveGLthanChar(dirtyBlock);
    $("#comments").val(cleanedBlock);
    this.submit();
});