简体   繁体   中英

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. 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

"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

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?

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 "...

Update:

Odd, it doesn't look like any JavaScript/JSON escaping you'd expect. You can have forward slashes in JavaScript strings just fine.

Why dont you try a regex on the escaped slashes to replace them in the C# code...

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 .

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