本文介绍了添加“/路径/"在 JavaScript 中的 URL 中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何有效地在 JavaScript 中的 URL 中间添加路径"?

How can I effectively add a "path" to the middle of an URL in JavaScript?

我想将 embed 添加到 URL,因此 URL https://blog.com/post/123 最终看起来像这样 https://blog.com/embed/post/123?

I want to add embed to an URL, so the URL https://blog.com/post/123 will end up looking like this https://blog.com/embed/post/123?

干杯

推荐答案

您可以创建一个 并设置 href 属性.然后在路径名前加上 embed 并使用 toString() 获取整个 URL.

You can create an <a> and set the href property. Then prepend embed to the pathname and use toString() to get the whole URL.

let element = document.createElement('a');
element.href = 'https://blog.com/post/123';
element.pathname = 'embed' + element.pathname;
console.log(element.toString());

这篇关于添加“/路径/"在 JavaScript 中的 URL 中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 13:06