Javascript 替换字符串中的字符 *、+ 和 /
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3632658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript replacement of the characters *, +, and / within a string
提问by Hyman Orjill
Alright, so I'm currently working on a simplistic manner of mimicking the function of PHP's urlencode() with JS's escape() and some string replacement. I'm purely looking at keyboard characters, so no special ASCII or Unicode characters. The problem I'm encountering is that the specific characters *, +, and / all have special meanings in RegExp, and seeing as JavaScript String Object methods use RegExp parameters, I cannot fully replicate PHP's urlencode(). Thus, how would one manage to perform a replacement of these characters within a string using JS?
好的,所以我目前正在以一种简单的方式使用 JS 的 escape() 和一些字符串替换来模仿 PHP 的 urlencode() 的功能。我纯粹是在看键盘字符,所以没有特殊的 ASCII 或 Unicode 字符。我遇到的问题是特定字符*、+和/在RegExp中都有特殊含义,并且由于JavaScript String Object方法使用RegExp参数,我无法完全复制PHP的urlencode()。因此,如何使用 JS 设法替换字符串中的这些字符?
Background information:
escape() discrepancies with urlencode():@: not converted, should be %40&: considered an html entity, thus is escaped as %26amp%3B rather than %26*: not converted, should be %2A+: not converted, should be %2B/: not converted, should be %2F<: considered an html entity, thus is escaped as %26lt%3B rather than %3C>: considered an html entity, thus is escaped as %26gt%3B rather than %3E
背景信息:
escape() 与 urlencode() 的差异@::未转换,应%40&:被视为 html 实体,因此转义为 %26amp%3B 而不是%26*:未转换,应%2A+:未转换,应%2B/:未转换,应该是%2F<:被视为 html 实体,因此被转义为 %26lt%3B 而不是%3C>:被视为 html 实体,因此被转义为 %26gt%3B 而不是%3E
HTML Entity conversion is as simple as
HTML实体转换就这么简单
str.replace(/&/g, '%26').replace(/</g, '%3C').replace(/>/g, '%3E');
and @can be replaced, as it is not a reserved RegExp character.*represents the {0}conditional+represents the {1}conditional/is the basic RegExp tag character
并且@可以替换,因为它不是保留的 RegExp 字符。*表示{0}条件+表示{1}条件/是基本的 RegExp 标签字符
Thank you for your time.
感谢您的时间。
回答by 15ee8f99-57ff-4f92-890c-b56153
Is there a reason not simply to escape the *, +, and / characters with backslashes in the regex?
是否有理由不简单地在正则表达式中使用反斜杠转义 *、+ 和 / 字符?
s = s.replace( /\*/g, 'star' );
回答by Casey Chu
To me, chaining replaces isn't very elegant. I would try:
对我来说,链接replaces 不是很优雅。我会尝试:
var symbols = {
'@': '%40',
'&': '%26',
'*': '%2A',
'+': '%2B',
'/': '%2F',
'<': '%3C',
'>': '%3E'
};
str = str.replace(/([@*+/]|&(amp|lt|gt);)/g, function (m) { return symbols[m]; });
Conveniently, this also avoids the original problem.
方便的是,这也避免了原来的问题。
回答by Mahir
You can always use good ole' string array access.
您始终可以使用良好的 ole' 字符串数组访问。
var myString = "Hello this is a string. * It contains an asterisk.";
for(var i = 0; i < myString.length; i++)
{
if(myString[i] == '*')
{
alert(i);
}
}?
回答by Patrick Reilly
Sorry that I'm not using the same account, but to respond to all, here goes:
抱歉,我没有使用同一个帐户,但为了回应所有人,这里是:
Mr. Plunkett, escaping the characters actually doesn't work in this case, for whatever reason (probably due to their reserved character status). I forgot to mention that I tried escaping them xD.
Plunkett 先生,无论出于何种原因(可能是由于它们的保留字符状态),在这种情况下转义字符实际上不起作用。我忘了提到我试图逃避他们 xD。
Mr. Hope, thank you for the bypass solution. I'll check that out and see if it works (it should).
Hope 先生,感谢您提供绕过解决方案。我会检查一下,看看它是否有效(应该)。
Mahir (?????), Firstly, string array access would be a very very lengthy addition of code, especially when dealing with three extra characters that need to be replaced (yes, I know, it could just be an if/else if/else if, but that's still quite a bit of code). Oui, et bien ?a suffit de dire qu'il est mon caractère favorit de la littérature Fran?aise.
Mahir (?????),首先,字符串数组访问将是一个非常非常冗长的代码添加,尤其是在处理需要替换的三个额外字符时(是的,我知道,它可能只是一个 if/else if/else if,但这仍然是相当多的代码)。Oui, et bien ?a suffit de dire qu'il est mon caractère favourit de la littérature Fran?aise。
With regards to William's response, if you do a bit of research, you'll notice that encodeURIComponent() does not actually encode a multitude of characters which are encoded by PHP's urlencode(). The object of this entire question was to build a simple replica of urlencode() within JS.
关于 William 的回应,如果您进行一些研究,您会注意到 encodeURIComponent() 实际上并未对由 PHP 的 urlencode() 编码的大量字符进行编码。整个问题的目的是在 JS 中构建 urlencode() 的简单副本。
So thank you all for responding, it is much appreciated.
所以谢谢大家的回复,非常感谢。
--addendum--
Mr. Hope's code works, with a single tweak:
--addendum--
Hope 先生的代码有效,只需进行一次调整:
function urlencode(str) {
var symbols = {
'@': '%40',
'%26amp%3B: '%26',
'*': '%2A',
'+': '%2B',
'/': '%2F',
'%26lt%3B': '%3C',
'%26gt%3B': '%3E'
};
return escape(str).replace(/([@*+/]|%26(amp|lt|gt)%3B)/g, function (m) { return symbols[m]; });
}
Obviously someone else might change the code a different way to make it work, but for me, eliminating the crosstalk from escaping the percentage signs of the replacements is much more convenient.
显然,其他人可能会以不同的方式更改代码以使其工作,但对我而言,消除串扰以避开替换的百分比符号要方便得多。
Thank you all, once again.
再次感谢大家。

