使用字符串替换使用 Javascript 和 jQuery 替换冒号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6524982/
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
Replacing a colon using string replace using Javascript and jQuery
提问by tollmanz
I have a simple string that I'm trying to manipulate:
我有一个要操作的简单字符串:
Your order will be processed soon:
您的订单将很快得到处理:
I grab the string using:
我使用以下方法抓取字符串:
var html = jQuery('.checkout td h4').html();
I then try to replace the ':' using:
然后我尝试使用以下方法替换“:”:
html.replace(":", ".");
When I print it out to the console, the string is the same as the original string. I've also tried making sure that the html
variable is of type "string" by doing the following:
当我将其打印到控制台时,该字符串与原始字符串相同。我还尝试html
通过执行以下操作来确保变量的类型为“字符串”:
html = html + "";
That doesn't do anything. In searching around, it seems that the replace
function does a RegEx search and that the ":" character might have a special meaning. I do not know how to fix this. Can someone help me get rid of this stinkin' colon?
那没有任何作用。在四处搜索时,该replace
函数似乎执行了 RegEx 搜索,并且“:”字符可能具有特殊含义。我不知道如何解决这个问题。有人能帮我摆脱这个臭冒号吗?
回答by Chrisdigital
Slightly related...
有点关系...
I couldn't get these answers to work to replace all ":" in a string for the url encoded character %3a and modified this answer by'xdazz' to work: Javascript: Replace colon and comma charactersto get...
我无法得到这些答案来替换 url 编码字符 %3a 的字符串中的所有“:”,并通过“xdazz”修改了此答案以使其工作:Javascript:替换冒号和逗号字符以获取...
str = str.replace(/:\s*/g, "%3a");
In your case it would be
在你的情况下,它会是
str = str.replace(/:\s*/g, ".");
If you wanted to replace all colons with periods on a longer string.
如果您想用更长的字符串上的句点替换所有冒号。
Hope this helps somebody else.
希望这对其他人有帮助。
回答by SLaks
The replace
function returns a new string with the replacements made.
Javascript strings are immutable—it cannotmodify the original string.
该replace
函数返回一个带有替换的新字符串。
Javascript 字符串是不可变的——它不能修改原始字符串。
You need to write html = html.replace(":", ".");
你需要写 html = html.replace(":", ".");
回答by Dunes
I think c++ is the only high level language where strings are mutable. This means that replace
cannot modify the string it operates on and so must return a new string instead.
我认为 c++ 是唯一一种字符串可变的高级语言。这意味着replace
不能修改它所操作的字符串,因此必须返回一个新字符串。
Try the following instead
请尝试以下操作
var element = jQuery('.checkout td h4');
element.html(element.html().replace(":", "."));
Or, perhaps more correctly (since you may have multiple elements).
或者,也许更正确(因为您可能有多个元素)。
jQuery('.checkout td h4').html(
function (index, oldHtml) {
return oldHtml.replace(":", ".");
}
);