character พิเศษบางตัวที่จะทำ syntax ของ javascript มัน error

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: character พิเศษบางตัวที่จะทำ syntax ของ javascript มัน error

character พิเศษบางตัวที่จะทำ syntax ของ javascript มัน error

โดย jataz2 » 31/07/2019 9:14 am

ถ้าเพื่อนๆ เขียน .net web application และต้องการ alert ข้อความที่ error code behind ตอนเกิด catch exception เช่น StackTrace
ให้เห็นบนหน้าเว็บได้ชัดๆ ข้อความใน StackTrace มันอาจจะมีทั้่ง tab ตัวขึ้นบรรทัดใหม่ อักษร ' หรืออักษร "
เมื่อส่งไปแสดงผลที่หน้าเว็บ javascript alert มันจะเกิด error หน้าเว็บ

ยกตัวอย่างเช่น StackTrace มีค่าดังนี้ Can not process your reqest because field 'CountryName' exceed maximum length
จะสังเกตุว่าภายในข้อความมีเครื่องหมาย '

alert('Can not process your reqest because field 'CountryName' exceed maximum length');

พอเป็นแบบนี้มันจึงทำให้ syntax ของ javascript alert มันผิดเพราะตัดคำสิ้นสุดลงแล้ว

alert('Can not process your reqest because field 'CountryName' exceed maximum length');

วิธีแก้คือ เราต้อง replace อักขระพิเศษใน StackTrace ออกให้หมดก่อน โดยใช้ code ด้านล่างนี้ได้

โค้ด: เลือกทั้งหมด

public static string RemoveLineEndings(string value)
        {
            if (String.IsNullOrEmpty(value))
            {
                return value;
            }
            string lineSeparator = ((char)0x2028).ToString();
            string paragraphSeparator = ((char)0x2029).ToString();

            return value.Replace("\r\n", string.Empty)
                        .Replace("\n", string.Empty)
                        .Replace("\r", string.Empty)
                        .Replace("\b", string.Empty)
                        .Replace("\f", string.Empty)
                        .Replace("\t", string.Empty)
                        .Replace("\\", string.Empty)
                        .Replace("'", string.Empty)
                        .Replace("\"", string.Empty)
                        .Replace(lineSeparator, string.Empty)
                        .Replace(paragraphSeparator, string.Empty);
        }

ข้างบน