javascripthtmlrazorpdf.jspdfobject

Escape apostrophes in dynamic strings using javascript


I have a list of file names that are being dynamically generated using .NET's Directory.Enumerate. When ever I try to view a file that includes an apostrophe and try to render it the string is cut off at the '. I tried using string.replace but its not helping. One example is \\shared_directory\PDFs\Resumes\...\O'Greene_Rick G.pdf. When I try to open the file using PDF.js I get an error saying 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>
 }

generated html item

<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>

Solution

  • I was able to resolve it by replacing ' with %27.

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