0

If there is a url where i need to remove the timestamp part of it. How would i do it in 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.

4
  • t%22%3A1378328815840%7D, this is what i need to remove from teh url, it is the timestamp Commented Sep 4, 2013 at 21:14
  • You want to actual remove that part from the url, or retrieve the url in a string and then edit that string ? In both cases, a simply look over developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… should make it clear. Commented Sep 4, 2013 at 21:16
  • i need to remove that part from teh existing url Commented Sep 4, 2013 at 21:19
  • The %7D is a close bracket in most character sets, and probably corresponds to the %7B at the start of the input, so is probably not part of the timestamp. Are you sure you want to remove it too? Commented Sep 4, 2013 at 21:27

1 Answer 1

3

Since this encodes a JSON string

{"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.


This code also might also do strange things if the URI is not UTF-8 encoded and contains non-ASCII code-points.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.