Breaking Down URLs with JavaScript

I am looking to extract specific portions of a URL and here is my progress so far.

<script type='text/javascript'>
var query = window.location.pathname.split( '/' );
query = window.location.pathname.split( '.html' );

var redirectpath = "http://www.mydomain.com/search/?q="
window.location.href = redirectpath + query;
</script>

URL structure example:

http://www.mydomain.com/page/2013/05/some-page-title.html

The query variable outputs as follows: page,2013,05,some-page-title

I am interested in only the some-page-title part and would like to remove any hyphens.

Therefore, the final output should be

http://www.mydomain.com/search/?q=some page title

Any suggestions on achieving this? Your help would be greatly appreciated! Thank you

Answer №1

If you need to extract a specific part of a URL, the split function can be your best friend!

var urlParts = window.location.pathname.split( '/' );
var targetPart = urlParts[urlParts.length-1].split( '.html' );

targetPart[0]= targetPart[0].replace(/-/g," ");   

var redirectURL = "http://www.mywebsite.com/search/?q="
window.location.href = redirectURL + targetPart[0];

This code snippet assumes that you always want the segment of the URL appearing after the last /

Answer №2

//extract the current URL
                                var url = window.location;
                                
                                //function to extract hostname and pathname
                                //var l = getLocation(url);
                                
                                //split the pathname by /
                                var array = url.pathname.split('/');

                                //prepare the base URL for concatenation
                                var pathnames = window.location.protocol + "//" + window.location.host;

                                //iterate through each part of the split URL and insert them into specific div
                                for (i = 1; i < array.length; i++) {

                                    //concatenate the path with each loop iteration
                                    pathnames = pathnames + '/' + array[i];

                                    //append an anchor tag with href for each part of the path to the element with id table_panel_header
                                    $("div#table_panel_header").append(
                                            '<a href="' + pathnames + '">'
                                                    + array[i] + '</a>/');
                                }

                                //example text displayed as: Complaint_Module/master/complaint-items/

                               /* example  href will be appended like
                               <div id="table_panel_header">
                                <a href="http://localhost:8010/Complaint_Module">Complaint_Module</a>/
                                <a href="http://localhost:8010/Complaint_Module/master">master</a>/
                                <a href="http://localhost:8010/Complaint_Module/master/complaint-items">complaint-items</a>/
                                </div> */

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

Is it possible in Angular.js to limit the visibility of a service to only one module or to a specific group of modules?

When working with Angular.js, the services declared on a module are typically accessible to all other modules. However, is there a way to restrict the visibility of a service to only one specific module or a selected group of modules? I have some service ...

Issues with passing Angular directive attributes to the scope were encountered

I am having an issue with my angular directives where the arguments are not being passed into the scope: app.directive('sectionLeft', function() { return { restrict:'E', scope: { sectionContent: '=', s ...

Utilizing Jquery to add a delay and animate the sliding up effect on a recently created element

I am looking to apply a slide-up effect to a newly created element after a specified delay. $("div[data-error='true']").delay(5000).slideUp(500, function () { $("#error-alert").remove(); }); $("div[data-success='true']").delay(5000 ...

Double clicking on a row value in a Bootstrap table

Struggling to retrieve the row value after a double click in a bootstrap table. Unfortunately, every attempt returns 'undefined'. Snippet of my code: $('#table').on('dbl-click-row.bs.table', function(field, value, row, $el) ...

What is the name of the JavaScript code editor that includes line numbering for plain text?

Looking to incorporate a text area with line numbering features. I experimented with EditArea, but encountered difficulties when working with text files. While syntax highlighting for various programming languages would be a nice touch, my primary focus ...

Convert a string into a PHP associative array

Is there a way to transform the following string into an actual PHP associative array? $str = "array('3'=>'wwm','1'=>'wom')"; I need help converting it to a real PHP associative array... ...

Exploring the contents of a dropdown menu by navigating through a tree structure in React JS

A unique custom component has been developed, featuring a dropdown with a tree-like structure inside that allows users to search for values. However, it seems that the search function only works after reaching two levels of the tree structure. Currently, ...

Encountering a malfunction while executing an npm command specified in the package.json file

Currently, I am following a tutorial on Node, React, and Express on Udemy. In the tutorial, when I execute the command npm run data:import I encounter the following error: undefined npm ERR! code ELIFECYCLE npm ERR! errno 1 ...

creating a personalized CSS style rule

Can a custom rule be created in CSS using @media for a parent class to make changes based on the class? <div class="parentGreen"> <ul class="ul1"> <li>1</li> <li>2</li> &l ...

Redux - Preventing Overwriting of Product Quantity in Cart by Creating a New Object

Is there a way to address the issue where adding the same product multiple times to the cart creates new objects instead of increasing the quantity? switch (action.type) { case actionTypes.ADD_TO_CART: const product = state.products.find((p) = ...

Steer clear of using the array push method repeatedly

I have recently developed an object that contains an array. Within this array, I am pushing objects from JSON data. $scope.pagenumArr = {"attribute":[],"_name":"pagenum","__prefix":"xsl"}; if ($scope.pagenumArr.attribute.indexOf($scope.content ...

Reposition HTML elements using JavaScript

Is there a way to use JavaScript or jQuery to replace the image with class "fnone" located under the span element with class "ddlabel"? <span id="flat_title" class="ddTitleText "> <img class="fnone" src="images/pinc.png"> <span ...

Is it possible to launch a React application with a specific Redux state preloaded?

Is there a way to skip navigating through a bulky frontend application in order to reach the specific component I want to modify? I'm curious if it's feasible to save the redux store and refresh my application after every code alteration using t ...

Transfer the array using Ajax to a PHP script

I have an array generated using the .push function that contains a large amount of data. What is the most effective way to send this data to a PHP script? dataString = ??? ; // Is it an array? $.ajax({ type: "POST", url: "script.php" ...

The code functions properly when run locally, however, it encounters issues when deployed

When testing the following lambda code locally using Alex-app-server, everything works perfectly fine. However, when I publish it and test on AWS Lambda, it gets stuck within the else statement. It prints the console log 'OUT PUBLISH' but doesn&a ...

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...

retrieving particular information from within a Firebase array

My Firebase document contains a list with various properties such as name and imgUrl. Currently, I am facing an issue with extracting only the "name:" information from the list in Firebase Cloud Firestore so that I can determine how many times a specific n ...

Creating JSON data based on user provided input within a text area

I am currently developing an application that requires a json datafile to generate certain elements. I am looking to gather user input through this form: { "nodes": [ { "id": "n0", "label": "A node", "x": 0, "y": 0, "si ...

Retrieving JSON data with jQuery's Ajax functionality

I'm currently developing a web application to handle the administrative tasks for a restaurant. The main functionalities include creating new orders, adding order items, and managing financial overviews. One of the key features is the ability to view ...

Adding content to an empty element will not produce the desired result

I'm trying to show each character of a string, which is stored in an array, one at a time. However, when I use threadsleep(a) with the code found here: http://jsfiddle.net/thefiddler99/re3qpuoo/, all the characters are displayed at once. There seems t ...