JavaScript是否支持逐字字符串?

Mic*_*out 19 javascript string

在C#中,你可以使用这样的逐字字符串:

@"\\server\share\file.txt"
Run Code Online (Sandbox Code Playgroud)

JavaScript中有类似的东西吗?

Joh*_*ren 13

模板字符串确实支持换行符.

`so you can
do this if you want`
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

它当然不会阻止文本中的扩展,并且通过扩展,代码执行,但这可能是一件好事吗?

注意:我认为没有办法获取现有字符串并通过表达式插值运行它.这使得无法以这种方式注入代码,因为代码必须源自源代码.我不知道可以按需进行表达式插值的API.

注2:模板字符串是ES2015/ES6功能.支持每个浏览器,除了(等待它......)IE!但是,Edge确实支持模板字符串.

注3:模板字符串扩展转义序列,如果字符串中有一个字符串,该字符串将扩展其转义序列.

`"A\nB"`
Run Code Online (Sandbox Code Playgroud)

......将导致:

"A
B"
Run Code Online (Sandbox Code Playgroud)

...这将无法使用,JSON.parse因为现在字符串文字中有一个新行.可能很高兴知道.


Tim*_*uri 10

不,在JavaScript中不支持.而这种解决方法似乎很成问题,因为你现在失去了使用正斜杠的能力.

当我需要从ASP.NET后端构建警报消息或其他内容时,我自己遇到了这个问题,并将其粘贴在前端的JavaScript警报中.问题是开发人员可以在Page.Alert()方法中输入任何内容.

我做了解决这个问题的方法如下:

public void Alert(string message)
{
    message = message.Replace("\\", "\\\\")
        .Replace("\r\n", "\n")
        .Replace("\n", "\\n")
        .Replace("\t", "\\t")
        .Replace("\"", "\\\"");

    // and now register my JavaScript with this safe string.
}
Run Code Online (Sandbox Code Playgroud)

  • 这只是一个例子,非常适合给定的问题(Windows路径).你可以替换/任何角色. (2认同)

Lit*_*ore 9

只需使用 String.raw()

String.raw`\n`
Run Code Online (Sandbox Code Playgroud)

会输出

\\n
Run Code Online (Sandbox Code Playgroud)

但我不知道如何解决这个案子:

String.raw`hello`hello`  // It will throw an TypeError
String.raw`hello\`hello` // Output is 'hello\\`hello'
Run Code Online (Sandbox Code Playgroud)

我不知道如何处理`:(


est*_*ani 5

这是一个非常老的线程,但仍然是一个解决方法:

function verbatim(fn){return fn.toString().match(/[^]*\/\*\s*([^]*)\s*\*\/\}$/)[1]}
Run Code Online (Sandbox Code Playgroud)

您将使用哪个:

var myText = verbatim(function(){/*This
 is a multiline \a\n\0 verbatim line*/})
Run Code Online (Sandbox Code Playgroud)

基本上这里发生的是js将评论确实视为逐字字符串.此外,这些与功能一起存储.所以这里发生的是我们创建一个带有一些逐字注释的函数,我们在逐字函数中提取这些注释.

  • 我不知道为什么所有关于转义字符和替换字符串的讨论似乎与逐字逐字相反 - 尽管 OP 在编程和 JS 之间进行了比较,但他没有说明他需要它们之间的互操作性。这个答案以一种优雅而令人惊讶的方式起作用 - 它让我的一天变得明亮!但只是复制 JS 给了我错误“无法获取未定义或空引用的属性 '1'”。将 return 语句更改为 `return fn.toString().split("/*")[1].split("*/")[0]` 以仅获取注释之间的所有内容都满足我的需要。感谢。 (2认同)

Num*_*riq 5

是的,我们可以使用 static String.raw()。它是在 ECMAScript 6 (ES6) 中引入的。这类似于 Python 中的 r 前缀,或 C# 中字符串文字的 @ 前缀。

这用于获取模板字符串的原始字符串形式(即原始的、未解释的文本)。

句法:

String.raw(callSite, ...substitutions)
or 
String.raw`template string`
Run Code Online (Sandbox Code Playgroud)

例子:

const filePath_SimpleString = 'C:\\Development\\profile\\aboutme.html';
const filePath_RawString = String.raw`C:\Development\profile\aboutme.html`;
  
console.log(`The file was uploaded from: ${filePath}`);
console.log(`The file was uploaded from: ${filePath}`);
 
// expected output will be same: 
//"The file was uploaded from: C:\Development\profile\aboutme.html"
Run Code Online (Sandbox Code Playgroud)