简体   繁体   English

使用C#删除无效的JavaScript令牌

[英]Remove invalid javascript tokens using C#

I write out a script on my page that looks like this: 我在我的页面上写了一个如下所示的脚本:

<script type="text/javascript">
var test = 'Some user input';
</script>

Some user input comes from my C# code and was previously saved by a user. 某些用户输入来自我的C#代码,之前已由用户保存。 Now, the problem is, that from time I will get the following error in the browser: 现在,问题是,从那时起我将在浏览器中收到以下错误:

Uncaught SyntaxError: Unexpected token ILLEGAL 未捕获的SyntaxError:意外的标记ILLEGAL

I need some generic way of catching these illegal characters and remove them. 我需要一些通用的方法来捕获这些非法字符并删除它们。 For example, the following user input actually contains an illegal character: 例如,以下用户输入实际上包含非法字符:

<p><span>.</span></p>

I've actually had to remove the illegal character here in the Stackoverflow question because it also breaks the editor here - instead I've added the unspoiled example here in jsfiddle: https://jsfiddle.net/p8suow9m/ 我实际上必须删除Stackoverflow问题中的非法字符,因为它也打破了编辑器 - 而是我在jsfiddle中添加了未受污染的示例: https ://jsfiddle.net/p8suow9m/

It's hard to see, but it's there. 很难看到,但它就在那里。 Looking at it in Google Chrome makes it a little easier to see: 在谷歌浏览器中查看它可以让它更容易看到:

在此输入图像描述

Can someone help me with the right approach in C# to filter away these illegal characters? 有人可以用C#中的正确方法帮助我过滤掉这些非法字符吗?

Note that I cannot use an approach that uses a list of valid characters and removes everything else, because I do need to support a lot of special characters that are legal in a javascript string. 请注意,我不能使用使用有效字符列表的方法并删除其他所有内容,因为我需要支持许多在javascript字符串合法的特殊字符。

尝试以下c#代码,它对我有用:PS:无法将其作为代码发布,编辑器错误,所以我错过了代码片段的事情。

 Regex.Replace(@"<p><span>test. > </span></p>", @"[^\-\]", string.Empty); 

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

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