解码(循环)直到字符串URI相同

时间:2018-10-05 11:47:45

标签: javascript loops uri decode

我希望对字符串URI进行解码,直到没有变化为止。 通常,字符串URI大约有53'000个字符。因此比较应该很快。在我的示例代码中,我使用了字符串的简短形式。

这是我的示例代码,很不幸,它无法正常工作:

var uri = "https%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab_VERY_LONG_URL"
var firstDecode = decodeURIComponent(uri.replace(/\+/g,  " "));
var res = Decode(firstDecode);

function Decode(firstDecode){
    var secondDecode = decodeURIComponent(uri.replace(/\+/g,  " "))
    while (firstDecode.localeCompare(secondDecode) != 0) {
        firstDecode = decodeURIComponent(uri.replace(/\+/g,  " "))
    }

  return firstDecode;
}


/* Expected Returns:
localeCompare()
 0:  exact match
-1:  string_a < string_b
 1:  string_a > string_b
 */

如何用最流畅的方式做到这一点? 预先感谢。

更新1

确定我的代码的新版本:

var uri = "https%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab_VERY_LONG_URL"
var res = Decode(uri);

function Decode(uri){
    var initialURI = URI
    var newURI = decodeURIComponent(uri.replace(/\+/g,  " "));

    If (initialURI === newURI) {
        // no changes anymore
        return newURI;
    } else {
        // changes were detected, do this function again
        var res = Decode(newURI);
    }
}

但是它仍然无法正常工作。

1 个答案:

答案 0 :(得分:0)

您要递归地对某些encoded URI进行解码,直到 decode 不再更改result了?

如果我的理解正确,请参见以下内容:

/* Suppose our sample case is a recursively encoded URI */

let URIEncoded = "https%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab_VERY_LONG_URL"
console.log('URI ENCODED ONCE:', URIEncoded)

let URIEncodedTwice = encodeURIComponent(URIEncoded)
console.log('URI ENCODED TWICE:', URIEncodedTwice)

let URIEncodedThrice = encodeURIComponent(URIEncodedTwice)
console.log('URI ENCODED THRICE:', URIEncodedThrice)


/* Get the original URI */
let baseURI = decodeNestedURI(URIEncodedThrice);
console.log('BASE URI:', baseURI) // print result

/* function decodeNestedURI returns the base URI of one that's been encoded multiple times */
function decodeNestedURI(nestedURI) {
    let oldURI = nestedURI
    let newURI = null
    let tries = 0

    while (true) {
      tries++
      newURI = decodeURIComponent(oldURI);
      
      if (newURI == oldURI) break // quit when decoding didn't change anything
      
      oldURI = newURI
    } 
    console.log('TIMES DECODED:', tries-1) // -1 because the last decoding didn't change anything
    return newURI 
}

希望这会有所帮助。 干杯,