简体   繁体   English

逃脱JavaScript字符串的最佳方法? (json?)

[英]Best way to escape javascript string? (json?)

Using C# .net I am parsing some data with some partial html/javascript inside it (i dont know who made that decision) and i need to pull a link. 使用C#.net我正在解析其中包含一些部分html / javascript的数据(我不知道是谁做出的决定),我需要拉一个链接。 The link looks like this 链接看起来像这样

http:\/\/fc0.site.net\/fs50\/i\/2009\/name.jpg

It came from this which i assume is javascript and looks like json 它来自这个,我认为它是javascript,看起来像json

"name":{"id":"589","src":"http:\/\/fc0.site.net\/fs50\/i\/2009\/name.jpg"}

But anyways how should i escape the first link so i get http://fc0.site.net/fs50/i/2009/name.jpg 但是无论如何,我应该如何逃避第一个链接,以便获得http://fc0.site.net/fs50/i/2009/name.jpg

In this case i could just replace '\\' with '' since links dont contain \\ nor " so i could do that but i am a fan of knowing the right solution and doing things properly. So how might i escape this. After looking at that link for a minute i thought is that valid ? does java script or json escape / with \\? It doesnt seem like it should? 在这种情况下,我可以用“ \\”替换“ \\”,因为链接不包含“ \\”或“”,所以我可以做到这一点,但是我很乐于知道正确的解决方案并正确执行操作。因此,我如何才能逃脱这个问题。我以为那一分钟的链接是有效的吗?java脚本或json是否使用\\转义/?似乎不应该吗?

In your case: 在您的情况下:

"name":{"id":"589","src":"http://fc0.site.net/fs50/i/2009/name.jpg"}

"/" is a valid escape sequence. “ /”是有效的转义序列。 However, it is not required that / be escaped. 但是,不需要/进行转义。 You may escape it if you need to. 如果需要,可以将其转义。 The reason JSON explicitly allows escaping of slash is because HTML does not allow a string in a to contain "... JSON明确允许转义斜线的原因是因为HTML不允许其中的字符串包含“ ...”

Update: 更新:

Odd, it doesn't look like any JavaScript/JSON escaping you'd expect. 奇怪的是,它看起来不像您期望的任何JavaScript / JSON转义。 You can have forward slashes in JavaScript strings just fine. 您可以在JavaScript字符串中使用正斜杠就可以了。

Why dont you try a regex on the escaped slashes to replace them in the C# code... 为什么不在转义斜杠上尝试使用正则表达式以将其替换为C#代码...

String url = @"http:\/\/fc0.site.net\/fs50\/i\/2009\/name.jpg";

String pattern = @"\\/";

String cleanUrl = Regex.Replace(url, pattern, "/");

Hope it helps! 希望能帮助到你!

Actually you want to unescape the string. 实际上,您想取消转义字符串。 Answered in this question . 这个问题上回答

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

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