简体   繁体   English

仅转义 Javascript 中的“特殊”URI 字符

[英]Only escape “special” URI characters in Javascript

In JavaScript there are the two methods encodeURI() and encodeURIComponent() .在 JavaScript 中有两个方法encodeURI()encodeURIComponent() The former method only replaces special characters such as spaces, umlauts, accent marks, etc. The latter also replaces the reserved symbols , /? : @ & = + $前一种方法只替换空格、变音符号、重音符号等特殊字符。后者也替换保留符号, /? : @ & = + $ , /? : @ & = + $ and # . , /? : @ & = + $# But is there a method that replaces only these few reserved symbols and leaves special characters and umlauts intact?但是有没有一种方法可以替换这几个保留符号而保留特殊字符和元音变音?

If you have your own set of characters to replace, you could always do it yourself.如果你有自己的一组字符要替换,你总是可以自己做。 It's just string replacement:这只是字符串替换:

 const forbiddenChars = ",/?:@&=+$#".split('').reduce((acc, curr) => { acc[curr] = encodeURIComponent(curr); return acc; }, {}); const replaceIn = (input) => input.split('').map(char => forbiddenChars[char] || char).join(''); const myString = "hello / there, you"; console.log(replaceIn(myString));

Sorry about the poor performance of splitting the string and mapping over each char, you should probably not do that..抱歉,拆分字符串和映射每个字符的性能不佳,您可能不应该这样做..

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

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