简体   繁体   English

如何使用C#字符串转义单引号。替换为在HighCharts中使用?

[英]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. 在我的C#应用​​程序中,我使用用户输入来填充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 ' . 我遇到的问题是,当用户键入customer's它会导致应用程序崩溃,除非通过在'之前键入\\对其进行转义。

Here is the section in the Highcharts that I am filling in with the user input: 这是我用用户输入填写的Highcharts中的部分:

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 \\ . 然后替换为\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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