Keep deciphering in a loop until the URI string matches

I have a task to decode a string URI until there are no more changes. The string URI I am working with typically has around 53,000 characters, so the comparison needs to be fast. For demonstration purposes, I have used a shortened version of the string.

Below is the example code I have written, but unfortunately it is not functioning as expected:

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
 */

What is the best approach to achieve this task seamlessly? Thank you for any assistance.

Update 1

I have updated my code to a new version:

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);
    }
}

However, the issue still persists and the code does not work correctly.

Answer №1

Are you attempting to recursively decode an encoded URL, continuing until the decoding process no longer alters the result?

If I have grasped your query correctly, please refer to the solution presented below:

/* Let's assume we are dealing with a recursively encoded URL scenario */

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

let URLEncodedTwice = encodeURIComponent(URLEncoded)
console.log('URL ENCODED TWICE:', URLEncodedTwice)

let URLEncodedThrice = encodeURIComponent(URLEncodedTwice)
console.log('URL ENCODED THRICE:', URLEncodedThrice)


/* Obtain the original URL */
let baseURL = decodeNestedURL(URLEncodedThrice);
console.log('BASE URL:', baseURL) // output result

/* The function decodeNestedURL retrieves the original URL that has been repeatedly encoded */
function decodeNestedURL(nestedURL) {
    let oldURL = nestedURL
    let newURL = null
    let attempts = 0

    while (true) {
      attempts++
      newURL = decodeURIComponent(oldURL);
      
      if (newURL == oldURL) break // stop when decoding does not alter anything
      
      oldURL = newURL
    } 
    console.log('TIMES DECODED:', attempts-1) // -1 because the final decoding did not change anything
    return newURL 
}

I trust this explanation is beneficial. Regards,

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the syntax of Vue's data function

I encountered a syntax error while compiling my assets: Syntax Error: SyntaxError: C:\xampp\htdocs\dtcburger.com\resources\js\components\stripe\STRIPEform3.vue: Unexpected token, expected ";" (51:12) 49 | { ...

What is the process for setting a default value in an array using Angular and then showcasing that value in a textbox?

I have been working on creating a form that includes a feature to dynamically append new rows. While I am able to successfully create new rows dynamically, I am facing an issue with displaying the initial values in my textboxes. Below is a snippet of my c ...

What issue is arising from nesting jQuery for loops within another loop?

There seems to be an issue with wrapping the two "for loops" inside the first loop, although they work fine individually. Is there anyone who can point out what's wrong with them? jQuery('#rooms').change(function () { for (var a = 1; ...

gulp-open not functioning properly following the use of createWriteStream

I am utilizing gulp, gulp-eslint, and gulp-open to generate a report detailing ESLint outcomes. The linting and file creation processes function correctly; however, the task aimed at opening the file containing my report encounters issues. gulp.task(&apos ...

Retrieve the text content of a datalist option by accessing the label with jQuery

Utilizing data from a Json, I am populating a data-list in html. The options are added to the data-list with both value and label text. Upon clicking an option, I aim to insert both the value and text into a form text field. While accessing the option&apo ...

IE8 triggers automatic download upon receiving JSON response using jQuery

Can you help me make IE8 compatible with this code using jQuery to handle an ajax request that returns data as JSON? $.ajax({ url: formAction, type: 'post', dataType: 'json', data: form, success: ...

The Coinbase Pay application fails to compile properly due to a missing Babel loader

Currently, I am working on integrating the coinbase pay sdk into my project. Although I have successfully created a button utilizing their provided examples, I am encountering an issue during the build process which seems to be internal to their SDK. Spec ...

Provide a unique <li> attribute for the JavaScript function to utilize

Is there a way to pass specific attributes from dropdown options to a javascript function? I have tried using .data() and .attr(), but the console keeps showing "undefined". Any suggestions on how to achieve this in a cleaner and simpler way would be gre ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Easily toggle between different content within the same space using Twitter Bootstrap Tabs feature. Display the tabs

I made a modification to the bootstrab.js file by changing 'click' to 'hover': $(function () { $('body').on('hover.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.p ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

Converting an HTML table to a CSV file with pure JavaScript

I need to implement a CSV download feature on my website that converts the HTML table into downloadable content. While searching for a suitable plugin, I came across resources like http://www.dev-skills.com/export-html-table-to-csv-file/ which uses PHP s ...

Is there a way to exclude a specific div based on two select choices?

Check out my Fiddle demonstration here $('select#classes').on('change', function() { var selectedClass = $(this).val(); $('.col-sm-6:not(:contains(' + selectedClass + '))').hide(); $('select#subjec ...

Multiple jQuery AJAX requests triggered in a click event handler

I am in the process of developing a PHP web application and utilizing the datatables jQuery plugin along with jQuery AJAX calls to create a dynamic table for editing, deleting, and adding elements. Although it appears to be working correctly, I've not ...

employing iframes dynamically to overlay a webpage

I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...

Content in TinyMCE styled with the default CSS of the application

Hello fellow developers; I'm struggling to find a suitable solution to apply the same styles from our main CSS file to the text entered in the TinyMCE editor. Just to clarify, I don't want to alter the overall theme or appearance of TinyMCE itse ...

Why does JavaScript not wait for the completion of forEach and instead executes the next line immediately?

While creating my api in nodejs and attempting to push the mongoose return count to a newly created array, it does not wait for the forEach loop to finish before executing json.res() and returning a null response. However, when I use setTimeout(), the re ...

Performing a simulated click on a dynamically inserted element using pure JavaScript

I am faced with the challenge of programmatically navigating a ReactJS-based website in a looped workflow. The process involves clicking on Element1, dynamically altering the web page to add Element2, then clicking on Element2, and so on until eventually r ...

How to assign various column values to a PHP array in JSON format from a MySQL database

I am struggling with making a JSON Ajax request and receiving an array in return. After browsing through multiple questions, I came across this code snippet that I edited to fit my problem: var hej[]; function ajax_search(){ $.getJSON('test.php ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...