使用 jQuery 或 javascript 从字符串中删除特殊字符(&符号)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13493238/
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
Remove special character (ampersand) from a string with jQuery or javascript
提问by user795918
I'm trying to achieve something that 'should' be fairly straightforward, bit I can't find anything online to help me out.
我正在努力实现一些“应该”相当简单的东西,我在网上找不到任何东西来帮助我。
I have some CSS class names that are being output with ampersands in them (its down to the system I'm using and is unavoidable). I'd like to use a little bit of jQuery to simply remove the ampersand, so a string that looks like:
我有一些 CSS 类名在输出时带有 & 符号(这取决于我正在使用的系统并且是不可避免的)。我想使用一点点 jQuery 来简单地删除&符号,所以一个字符串看起来像:
class="Middle&East"
class="中东&"
would be
将是
class="MiddleEast"
类=“中东”
Any help with this would be very much appreciated.
对此的任何帮助将不胜感激。
Thanks
谢谢
回答by Alex K.
To replace them all you could;
尽你所能替换它们;
$('[class*=\&]').each(function() {
$(this)[0].className = $(this)[0].className.replace(/&/g,"");
})
?
回答by Shree
Try:
尝试:
var class="Middle&East"
class.replace('&', '');
回答by Clyde Lobo
You will have to escape the &
if you are using jquery
&
如果您使用 jquery ,则必须转义
Try
尝试
$(".Middle\\&East").removeClass("Middle&East").addClass("MiddleEast");
$(".Middle\\&East").removeClass("Middle&East").addClass("MiddleEast");
General solution to remove &
from classname
&
从类名中删除的通用解决方案
$(function(){
$('[class*="&"]').each(function(){
var $this = $(this),cname = $this.attr('class').replace(/&/g,'');
$this.attr('class',cname)
})
})
回答by sphair
Maybe something along
也许有什么
$(".Middle&East").removeClass("Middle&East").addClass("MiddleEast");
回答by Magus
This one seems to works for me :
这个似乎对我有用:
$(function() {
$('[class="Middle&East"]').toggleClass('Middle&East MiddleEast');
});
Here's a jsfiddle : http://jsfiddle.net/U3r7G/
这是一个 jsfiddle:http: //jsfiddle.net/U3r7G/
回答by Lukas1
var className = $(element).attr('class');
var modifiedClass = className.replace('&', '');
$(element).attr('class', modifiedClass);