如何同时替换字符和数字?
我有一个看起来像 - /celebrity.html#portfolios/jennifer-aniston-2006#img10
的字符串,
我想删除 #img10 (也可以是 #img6;实际上是任何数字)。
我使用了这段代码:
var docLoc = document.location.href.replace("#img", '');
var docLoc2= docLoc.replace(/[0-9]+/,'');
当我登录docLoc2时,我得到/celebrity.html#portfolios/jennifer-aniston-
我真的很想结合这两个替换函数,所以它一次完成所有操作,因此只会删除#img10。我还写了这个:
var docLoc = document.location.href.replace("#img"+/[0-9]+/, '');
这不起作用(我认为语法是错误的)。
有解决办法吗?
I have a string that looks like - /celebrity.html#portfolios/jennifer-aniston-2006#img10
I want to remove #img10 (which can also be #img6; any number really).
I have used this code:
var docLoc = document.location.href.replace("#img", '');
var docLoc2= docLoc.replace(/[0-9]+/,'');
When I log docLoc2, I get /celebrity.html#portfolios/jennifer-aniston-
I really want to combine these two replace functions, so it does it all at once, and therefore will only remove #img10. I have also written this:
var docLoc = document.location.href.replace("#img"+/[0-9]+/, '');
This doesn't work (I think the syntax is wrong).
Is there a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
.replace
MDN 文档< /sup> 适用于字符串或正则表达式。正如您自己指出的那样,您试图将两者与错误的语法结合起来......Use
.replace
MDN documentation works with either a string or a regular expression. You tried to combine both with the wrong syntax as you noted yourself...你的正则表达式可能是这样的
Your regex could be this