JavaScript是否支持逐字字符串?

时间:2008-11-12 10:00:18

标签: javascript string

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

@"\\server\share\file.txt"

JavaScript中有类似内容吗?

7 个答案:

答案 0 :(得分:13)

模板字符串支持换行符。

`so you can
do this if you want`

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

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

  

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

     

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

     

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

`"A\nB"`
     

...将导致:

"A
B"
     

...这不适用于JSON.parse,因为现在字符串文字中有一个新行。可能很高兴知道。

答案 1 :(得分:8)

不,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.
}

答案 2 :(得分:5)

这是一个非常古老的主题,但仍然是一个解决方法:

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

您将使用以下内容:

var myText = verbatim(function(){/*This
 is a multiline \a\n\0 verbatim line*/})

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

答案 3 :(得分:4)

解决方法的大问题......

<html>
<head>
<script>
function foo() {
    var string = document.getElementById('foo').innerHTML;
    alert(string);
}
window.onload=foo;
</script>
<style>
#foo{
  display: none;
}
</style>
</head>
<body>
Calling foo on page load.
<div id="foo">\\server\path\to\file.txt</div>
</body>
</html>

答案 4 :(得分:2)

我将重新讨论之前所说的内容 - 在javascript中无法使用逐字字符串。它实际上很容易逃脱有效的转义字符,如\n \\ \t等,但问题来自转义无效字符,因为它们在不同的函数中处理它们变得不兼容。例如

"\a".replace("\a","\\a")     // WORKS \a
"aa\a".replace("\a", "\\a")  // FAILS \aaa

此外,如果您查看一系列非法特殊字符,例如["\a"],该字符将看起来像a。这使得你想做的事情基本上不可能。

希望至少为你清除它。

答案 5 :(得分:2)

只需使用String.raw()

即可
String.raw`\n`

将输出

\\n

但我不知道如何解决此案:

String.raw`hello`hello`  // It will throw an TypeError
String.raw`hello\`hello` // Output is 'hello\\`hello'

我不知道如何处理` :(

答案 6 :(得分:2)

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

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

语法:

String.raw(callSite, ...substitutions)
or 
String.raw`template string`

示例:

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"
相关问题