简体   繁体   English

如何使用JavaScript删除URL的一部分

[英]how to remove a part of the url using javascript

If there is a url where i need to remove the timestamp part of it. 如果有一个网址,我需要删除它的时间戳部分。 How would i do it in javascript. 我将如何在JavaScript中做到这一点。

Regex or string operations which is preferred? 正则表达式或字符串操作是首选?

Here is the url , 这是网址,

"%7B%22def%22%3A%22f%3Ar%22%2C%22a%22%3A%7B%22v%22%3A%7B%22r%22%3A%22005x0000001R9JRAA0%22%7D%7D%2C%22t%22%3A1378328815840%7D"
                                                                                                      ^

t%22%3A1378328815840%7D , this is what i need to remove from the url, it is the timestamp. t%22%3A1378328815840%7D ,这是我需要从url中删除的内容,它是时间戳。

Since this encodes a JSON string 由于这会编码JSON字符串

 {"def":"f:r","a":{"v":{"r":"005x0000001R9JRAA0"}},"t":1378328815840} 

you can do 你可以做

function removeTimestamp(uriStr) {
  // Decode the JSON encoded in the URI.
  var jsonObj = JSON.parse(decodeURIComponent(uriStr));
  // Remove the "t" property.
  delete jsonObj['t'];
  // Re-encode as a URI-encoded JSON string
  return encodeURIComponent(JSON.stringify(jsonObj));
}

On your input string, 在您的输入字符串上,

var s = "%7B%22def%22%3A%22f%3Ar%22%2C%22a%22%3A%7B%22v%22%3A%7B%22r%22%3A%22005x0000001R9JRAA0%22%7D%7D%2C%22t%22%3A1378328815840%7D"

var sWithoutTimestamp = removeTimestamp(s);

alert(sWithoutTimestamp);

yields the first line below. 产生下面的第一行。 I've put a gap where the timestamp part was so you can easily compare it to the original. 我在时间戳部分的位置留了一段空白,以便您可以轻松地将其与原始时间戳进行比较。

Modified: %7B%22def%22%3A%22f%3Ar%22%2C%22a%22%3A%7B%22v%22%3A%7B%22r%22%3A%22005x0000001R9JRAA0%22%7D%7D                          %7D
Original: %7B%22def%22%3A%22f%3Ar%22%2C%22a%22%3A%7B%22v%22%3A%7B%22r%22%3A%22005x0000001R9JRAA0%22%7D%7D%2C%22t%22%3A1378328815840%7D

JavaScript doesn't specify key iteration order, and JSON.stringify 's output depends on key iteration order, so on some interpreters you might see reordering of properties, but it shouldn't affect the meaning of the output. JavaScript没有指定键迭代的顺序,而JSON.stringify的输出取决于键迭代的顺序,因此在某些解释器中,您可能会看到属性的重新排序,但不应影响输出的含义。


This code also might also do strange things if the URI is not UTF-8 encoded and contains non-ASCII code-points. 如果URI不是UTF-8编码的并且包含非ASCII代码点,则此代码也可能会做一些奇怪的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM