【问题标题】:Escape apostrophes in dynamic strings using javascript使用javascript转义动态字符串中的撇号
【发布时间】:2016-10-24 17:16:51
【问题描述】:

我有一个使用 .NET 的Directory.Enumerate 动态生成的文件名列表。当我尝试查看包含撇号的文件并尝试渲染它时,字符串在' 处被截断。我尝试使用 string.replace 但它没有帮助。一个例子是\\shared_directory\PDFs\Resumes\...\O'Greene_Rick G.pdf。当我尝试使用 PDF.js 打开文件时,我收到一条错误消息 Message: Unexpected server response (0) while retrieving PDF "http://shared_directory/Uploads/Resumes/.../O/"

javascript

 $('.file').on('click touchend', function (e) {
        e.preventDefault();
        if ($(this).hasClass('disabled'))
            return;
        var path = $(this).data('path').replace(/'/g, "\\'").replace("\\\\", "http://").replace("@pdfFolder", "Uploads");

cshtml

 foreach (var file in combinedFiles.OrderBy(f=> Path.GetFileNameWithoutExtension(f)).Where(f => Path.GetFileName(f).ToUpper().ToCharArray()[0] == letter))
 {
    <li class="file" data-path="@file" data-lastname="@Path.GetFileNameWithoutExtension(file).Split('_').Last() " data-name="@Path.GetFileNameWithoutExtension(file).Split('_').First() ">@Truncate(Path.GetFileNameWithoutExtension(file).Replace("_", ", "), 27)</li>
 }

生成的 html 项

<li class="file" data-path="\\shared_directory\PDFs\Resumes\O'Greene_Rick G.pdf" data-lastname="Rick G " data-name="O'Greene ">O'Greene, Rick G</li>

【问题讨论】:

  • 可能是时间问题。看起来您在错误的时间点进行更换。您应该在渲染之前替换您的 cshtml。
  • @TheBeardedLlama 我尝试使用data-path="@file.Replace("'", "\\'")",但没有帮助
  • 你能给我一个@file值的原始例子吗?
  • @TheBeardedLlama \\shared_directory\PDFs\Resumes\O'Greene_Rick G.pdf
  • 我认为无论是客户端还是服务器端,替换都不起作用;您也许应该查看您正在使用的库,因为可能有一个选项可以逃避您提供的路径或(已知)错误

标签: javascript html razor pdfjs pdfobject


【解决方案1】:

我能够通过将' 替换为%27 来解决它。

data-path="@file.Replace("'","%27")" 

【讨论】:

  • 终于到了! :)
猜你喜欢
  • 2011-02-08
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 2011-01-25
  • 2019-05-05
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
相关资源
最近更新 更多