最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Replace part of URL with JavaScript - Stack Overflow

programmeradmin0浏览0评论

I want to replace part of the URL with JavaScript but stupid regex is giving me headaches. I want to switch from this:

.html/post/something-else/

to this:

/

Any ideas? Thanks!

I want to replace part of the URL with JavaScript but stupid regex is giving me headaches. I want to switch from this:

http://website./test.html/post/something-else/

to this:

http://website./post/something-else/

Any ideas? Thanks!

Share Improve this question edited Mar 20, 2013 at 21:28 Alex asked Mar 20, 2013 at 21:03 AlexAlex 1,6063 gold badges18 silver badges35 bronze badges 6
  • What regexs have you tried – Gus Commented Mar 20, 2013 at 21:04
  • @Gus: url.replace(/\/test.html([^\/]+)$/, "\/$1");, var parts = url.split('/'); var img = parts.pop().replace("test.html", ""); parts.push(img) url = parts.join("/"); – Alex Commented Mar 20, 2013 at 21:06
  • Do you only want to remove "test.html" or are there more variants? – QuentinUK Commented Mar 20, 2013 at 21:06
  • @QuentinUK: no, only "test.html". I’m redirecting every page there. – Alex Commented Mar 20, 2013 at 21:07
  • "only 'test.html'" and "redirecting every page" seem to be opposites. Which do you mean? – Gus Commented Mar 20, 2013 at 21:11
 |  Show 1 more ment

1 Answer 1

Reset to default 6

Use replace() function

var url = 'http://website./test.html/post/something-else/'
url = url.replace('/test.html','')
console.log(url) // "http://website./post/something-else/"
发布评论

评论列表(0)

  1. 暂无评论