JavaScript 和字符串中的正斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6117886/
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:19:13  来源:igfitidea点击:

JavaScript and forward slashes in strings

javascript

提问by rubixibuc

What is the real reason that we must escape a forward slash in a JavaScript string, and also why must we escape string/no string in XHTML. A lot of tutorials just brush over this issue.

我们必须在 JavaScript 字符串中转义正斜杠的真正原因是什么,以及为什么我们必须在 XHTML 中转义字符串/无字符串。很多教程只是刷过这个问题。

回答by Quentin

What is the real reason that we must escape a forward slash in a JavaScript string

我们必须在 JavaScript 字符串中转义正斜杠的真正原因是什么?

In an HTML 4 document, the sequence </inside an element defined as containing CDATA (such as script) is an end tag and will end the element (with an error if it is not </script>.

在 HTML 4 文档中,</定义为包含 CDATA(例如脚本)的元素内的序列是结束标记,并将结束该元素(如果不是</script>.

As far as JS is concerned /and \/are identical inside a string. As far as HTML is concerned </starts an end tag but <\/does not.

就 JS 而言/\/在字符串中是相同的。就 HTML 而言,</开始一个结束标记,但<\/没有。

, and also why must we escape string/no string in XHTML.

,以及为什么我们必须在 XHTML 中转义字符串/无字符串。

XHTML doesn't provide a method of specifying that an element intrinsically contains CDATA, so you need to explicitly handle characters which would otherwise have special meaning (<, &, etc). Wrapping the contents of the element with CDATA markers is the easiest way to achieve this.

XHTML不提供指定的元素本质上包含CDATA的方法,所以你需要明确地处理,否则有特殊含义(字符<&等等)。使用 CDATA 标记包装元素的内容是实现此目的的最简单方法。

回答by rid

You don't need to escape /in a JavaScript string, just \, because if you don't, then the string yes\nowill inadvertently be transformed into yes<newline>o. Escaping the \will prevent that.

您不需要/在 JavaScript 字符串中转义,只需\,因为如果您不这样做,那么该字符串yes\no将在不经意间转换为yes<newline>o. 逃避\意志可以阻止这种情况。

Also, if you don't escape &in a URL, then whatever comes after it will be considered a new parameter. For example, a=Q&Awill mean "the parameter ahas the value "Q" and there's also a parameter A" instead of "the parameter ahas the value "Q&A"". The correct way of escaping that would be a=Q%26A.

此外,如果您不在&URL 中转义,那么后面的任何内容都将被视为新参数。例如,a=Q&A将意味着“参数a具有值“ Q”并且还有一个参数A“而不是“参数a具有值” Q&A“”。逃避的正确方法是a=Q%26A.

回答by densho

The slash is needed to prevent browsers, particularly older ones, to erroneously interpret the forward slash as a closing JavaScript marker.

需要使用斜杠来防止浏览器,尤其是较旧的浏览器,将正斜杠错误地解释为结束 JavaScript 标记。