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

Decode (loop) until string URI is the same

我想解码字符串 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);
    }
}

但它仍然不能正常工作。

您正在尝试递归解码一些encoded URI,直到解码它不会改变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 
}

希望这对您有所帮助。 干杯,