[英]jQuery / Javascript replace <space> in anchor link with %20
I'm new to jQuery and i'm trying to write some code to go through the page and rewrite anchor links href attribute so that spaces are removed and replaced with %20.我是 jQuery 新手,我正在尝试编写一些代码来浏览页面并重写锚链接 href 属性,以便删除空格并替换为 %20。
so far i have:到目前为止,我有:
$(".row a").each(function(){
$(this).attr("href").replace(/\s/g,"%20");
});
I've tried a few variations of this with no luck.我已经尝试了一些变体,但没有运气。
Your approach is correct, but you're forgetting to set the new value once you replace it.您的方法是正确的,但是您在替换后忘记设置新值。 Try this:尝试这个:
$(".row a").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});
You have to set the attribute value ( attr(key, value)
), in your code you are only reading its value:您必须设置属性值( attr(key, value)
),在您的代码中,您只读取其值:
$(".row a").each(function(){
$(this).attr('href', $(this).attr("href").replace(/\s/g,"%20"));
});
@Naresh Yes there is a way for that, see the below example: @Naresh 是的,有一种方法,请参见以下示例:
Decode a URI after encoding it:编码后解码 URI:
<script type="text/javascript">
var uri="my test.asp?name=ståle&car=saab";
document.write(encodeURI(uri)+ "<br />");
document.write(decodeURI(uri));
</script>
The output of the code above will be:上面代码的输出将是:
my%20test.asp?name=st%C3%A5le&car=saab
my test.asp?name=ståle&car=saab
You can replace ""
like so:您可以像这样替换""
:
$(document).ready(function () {
$("#content a").each(function (){
$(this).attr('href', $(this).attr("href").replace("%20",""));
});
});
我知道这太晚了,但我发现unescape()
方法也很有效......
in ES2021 use replaceAll()在 ES2021 中使用 replaceAll()
$(".row a").each( function() {
this.href = this.href.replaceAll('',"%20");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.