Working with Django urls in Javascript: Concatenating strings

I'm working on a basic URL builder project. In JavaScript, I have the following code snippet:

var url = document.URL;

To add something to the URL in Django, we can use the syntax below:

url = url + "{% url 'object_view' %}";
alert(url);

The issue arises when combining document.URL and Django's URL, resulting in a pattern like this:

http://localhost:8000//objects/view/

I've explored Javascript string manipulation methods such as trim() and replace(), but neither seems to offer a way to simply remove the extra slash from the document.URL string.

If I replace all slashes, it may cause problems if, for instance, my document.URL is structured as follows:

http://localhost:8000/something/something2/

Any ideas or suggestions?

Answer №1

If you're in a similar situation, try swapping out // unless it's preceded by :

"http://localhost:8000//objects/view/".replace( /(?<!:)\/\//g,  "/" )

Answer №2

Realized that removing the last / from the document.URL can be achieved using the slice() method.

var currentUrl = document.URL;
    currentUrl = currentUrl.slice(0, -1);
    alert(currentUrl);

Result:

http://localhost:8000

then add the rest of the URL:

currentUrl = currentUrl + "{% url 'routes_view' %}".toString();

Result:

http://localhost:8000/something/something2/

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

JS showcase of object literals and their corresponding properties

Just starting out with Javascript and eager to learn about arrays of objects. I'm currently exploring how to display an object along with its properties. Here's an example showcasing the colors of different fruits: var fruitColor = {'apples ...

Notifications for AngularJS tabs

I need help finding a method to incorporate "tab notification" using AngularJS, in order to show that there are important alerts that require attention. For example: (1) (3) TAB_ONE TAB_TWO TAB_THREE Could you provide any recom ...

The update depth has reached its maximum limit after attempting to setState upon the user's click action

Having trouble setting state when a user clicks on a list? I have a loop that generates a list of items in li tags, and I want to update the state when a user clicks on one of those li tags. However, React is throwing an error. The error message reads: " ...

Managed inputs versus FormData API

Recently, I came across a fascinating article that has the potential to revolutionize how web form submissions are handled in ReactJS moving forward. Check it out: https://medium.com/@everdimension/how-to-handle-forms-with-just-react-ac066c48bd4f What ar ...

Utilize the zoom functionality on an SVG that is already in place (using d3.js v4

I have been attempting to create a zoomable SVG using d3.js (version 4). You can view my progress here: JSFiddle HTML <svg id="mySVG" width="800px" height="600px" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); background: lightgrey;"> < ...

No reply from Axios after using async await

Here's a simple method that utilizes Axios to make a call to an API. Interestingly, when the method is called, it doesn't display any output, no logs or error messages. async deActivate(product: Product): Promise<void> { try { ...

Include the insertion button in the Tiny MCE Editor

Currently, I am in the process of developing my own plugin to integrate into the list of TinyMCE v4 plugins. So far, I have successfully added a button to the menu that opens a pop-up when clicked. In this pop-up, users can input data which is then added t ...

Enhancing Your Website - Customizing Image Sizes for Optimal Display

I have put in a fair amount of effort searching through Google and attempting to troubleshoot the issue on my own, but despite my limited knowledge, I am unable to determine how to properly scale my image using bootstrap. Essentially, I have two flex boxe ...

Is the creation and disposal of canvas objects in Chrome costly?

In order to keep my code simple, I prefer to create a temporary canvas for a specific task and discard it once I am finished, rather than attempting to reuse or readjust one single canvas repeatedly. Is there a definitive source or opinion that recommends ...

Dynamic parameters in the Vue router

Struggling to find the right syntax for passing dynamic param data. Experimented with multiple approaches, but I thought I could pass someValue like this: <router-link :to="{ name: 'Foo', params:{ bar: ${someValue} } }"> Unfortunately, co ...

Turn off eslint for specific NPM packages in Vue.js 2.x

In my Vue.js project, I have implemented a JavaScript client that was automatically generated using openapi-generator. However, the code generated has some shortcomings such as unused objects leading to eslint errors. Is there a way to selectively disabl ...

Utilize .GLB and Blender file formats within a Gridsome project developed with Vue.js

I am working on a project using Three.js in Gridsome, but I am facing difficulties importing .glb files (3D models) with GLTFLoader. While Gridsome recognizes img (png/jpg) or .js files stored in src/assets, it does not seem to support glb files. This is ...

Avoid displaying duplicate values when using Ng-repeat in Angular JS

I'm in search of a method to prevent the display of duplicate values when using ng-repeat with Angular JS. Here is an example of my JSON list: [ { "Country":"Algeria", "Value":"200" }, { "Country":"France", "Value":"300" }, { "Country":"France", "Va ...

Sending data through a form using the Fetch API to communicate with a Django View

As a novice, I am attempting to learn how to utilize both Django and the Fetch API. In my quest for knowledge, I came across this query regarding Django - taking values from POST request, JavaScript fetch API, which delves into the process of posting a fo ...

How can we dynamically extract the chosen value from a multiple selection using MaterializeCss?

(none of the similar questions provided me with a solution) Currently, I am utilizing the HtmlHelper @Html.ListBoxFor to generate a multiple select. However, I am encountering an issue where it generates the following structure: <ul id="select-option ...

When hovering over an object in three.js, the cursor should change on mouseover

In my scene, I have added a sphere and plane geometry. Clicking on the plane geometry will open a linked website. Now, when hovering over the plane geometry, I want the mouse cursor to change to a hand pointer icon, and revert back to its original style ...

Steps for clearing the UIWebView application cache for HTML5 applications

I recently encountered a problem where the HTML5 application cache stopped working in a native container using UIWebView to display HTML content. The cache.manifest file was updated, and UIWebView started downloading the process but failed at a specific ...

Troubleshooting: JQuery Ajax Post triggering 500 Internal Server Error

I've encountered an issue while trying to execute this AJAX post. Despite hitting break points in the controller, I keep receiving a server 500 error. It seems like the problem lies within the callback function. Any ideas on how to resolve this? $.aj ...

Issue with `npm run watch` failing to compile when the data source is turned

Currently, I am faced with a challenge while working on Laravel and utilizing various node packages for development. The issue at hand is my limited internet connectivity. Every time I attempt to execute npm run watch, it refuses to initiate unless I am c ...

The PWA manifest should have its start_url set to the present current_url

I am working on a Progressive Web App (PWA) and I have a 'manifest.json' file. I am looking for a way to automatically set the manifest's 'start_url' as the current URL when users install the app. Is there a method to achieve this? ...