修复/逃生的JavaScript转义字符?字符、JavaScript

2023-09-06 23:00:55 作者:活出别致的高傲

看this回答推理为何/转义和非特殊字符会发生什么

see this answer for reasoning why / is escaped and what happens on nonspecial characters

我有一个字符串,它看起来像这样解析后。此字符串来弗朗一个javascript行。

I have a string that looks like this after parsing. This string comes fron a javascript line.

var="http:\/\/www.site.com\/user"

我抓住报价的内侧,以便所有我已经是的http:\ / \ / www.site.com \ /用户。我如何正确地转义字符串?所以它的 http://www.site.com/user ?我使用.NET

I grabbed the inside of the quote so all i have is http:\/\/www.site.com\/user. How do i properly escape the string? so its http://www.site.com/user? I am using .NET

推荐答案

使用与string.replace()方法:

string expr = @"http:\/\/www.site.com\/user";  // That's what you have.
expr = expr.Replace("\\/", "/");               // That's what you want.

这,或者:

expr = expr.Replace(@"\/", "/");

请注意,上面不与空字符串替换出现的 \ ,以防万一,你必须支持包含其他合法反斜杠字符串。如果不这样做,你可以写:

Note that the above doesn't replace occurrences of \ with the empty string, just in case you have to support strings that contain other, legitimate backslashes. If you don't, you can write:

expr = expr.Replace("\\", "");

或者,如果你preFER常量文字:

Or, if you prefer constants to literals:

expr = expr.Replace("\\", String.Empty);