简体   繁体   中英

How do I escape a single quote using C# string.Replace to use in HighCharts?

In my c# application I am using user input to fill elements in HighCharts. The issue that I am running into is when a user types customer's it causes the application to break unless it is escaped by typing a \\ before a ' .

Here is the section in the Highcharts that I am filling in with the user input:

subtitle: {
    text: '<%=strDescription%>'
},

When adding records, instead of telling my users to type an \\ before typing a ' I want to do this for them automatically for them when I pull it out of the database and assign it to a variable. Here is what I have tried:

strDescription = reader1.GetString(0);
strDescription.Replace("'", "\'");

When I remove the slash from the user input it causes the application to break as if the string was not escaped. Note the following error:

subtitle: {
    text: 'This goal will be set once we have bench-marked the first quarter's results.'
},

How do I escape the single quote properly?

One way to do that is Invert the quotes - '' to ""

subtitle: {
    text: "<%=strDescription%>"
},

我最终使用它来解决我的问题。

strDescription = reader1.GetString(0).Replace("'", "\\'");

You can use lookahead.

(?=')

And then replace by \\ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM