开发者

How can i replace characters AND numbers at the same time

开发者 https://www.devze.com 2023-04-08 01:56 出处:网络
I have a string that looks like - /celebrity.html#portfolios/jennifer-aniston-2006#img10 I want to r开发者_JAVA百科emove #img10 (which can also be #img6; any number really).

I have a string that looks like - /celebrity.html#portfolios/jennifer-aniston-2006#img10

I want to r开发者_JAVA百科emove #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 2 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).

Can anyone provide me with a solution? Any replies are greatly appreciated.


Use

var docLoc = document.location.href.replace(/#img[0-9]+$/, '');

Demo at http://refiddle.com/1bq

update: added the $ at he end of the expression to only match the #img?? if it is at the end of the string, as suggested by Šime Vidas in the comments..


.replace MDN Docs 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

#img\d*
0

精彩评论

暂无评论...
验证码 换一张
取 消