使用 javascript 转义动态字符串中的撇号

Escape apostrophes in dynamic strings using javascript

我有一个使用 .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>

我可以通过将 ' 替换为 %27 来解决它。

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