在顺序很重要的 javascript 中,是否有更多的 eloquent 方法来编写字符串和符号替换?
Is there a more eloquent way to write a string and symbol replacement in javascript where order matters?
我正在使用几组字符串,除了一些符号外,我还删除了所有符号。一旦返回承诺,我就必须用 %20 替换 </code>(spaces) 。我现在有一个解决方案(减去一个更容易理解的问题的承诺)</p>
<pre><code>let ABC = "asvue ? ?. @@";
console.log(ABC
.replace(/[?]/g,'\?')
.replace(/[.]/g,'\.')
.replace(/[@]/g,'\@')
.replace(/[^a-zA-Z @.?]/g,'_')
.replace(/ /g,'%20'));
这给出了正确的结果 "asvue%20?%20?.%20@@"
但是否有更好或更多 eloquent 的方法来纠正这个问题?我也知道正则表达式不是必需的,但这只是我的一个老习惯。
正如@Bergi 所说,您应该使用 encodeURIComponent
,即 "replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character"。
let ABC = "asvue ? ?. @@";
console.log(encodeURIComponent(ABC)); // 'asvue%20%3F%20%3F.%20%40%40'
我正在使用几组字符串,除了一些符号外,我还删除了所有符号。一旦返回承诺,我就必须用 %20 替换 </code>(spaces) 。我现在有一个解决方案(减去一个更容易理解的问题的承诺)</p>
<pre><code>let ABC = "asvue ? ?. @@";
console.log(ABC
.replace(/[?]/g,'\?')
.replace(/[.]/g,'\.')
.replace(/[@]/g,'\@')
.replace(/[^a-zA-Z @.?]/g,'_')
.replace(/ /g,'%20'));
这给出了正确的结果 "asvue%20?%20?.%20@@"
但是否有更好或更多 eloquent 的方法来纠正这个问题?我也知道正则表达式不是必需的,但这只是我的一个老习惯。
正如@Bergi 所说,您应该使用 encodeURIComponent
,即 "replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character"。
let ABC = "asvue ? ?. @@";
console.log(encodeURIComponent(ABC)); // 'asvue%20%3F%20%3F.%20%40%40'