How to use split() Method In Javascript

This method is used to split a string into an array of substrings and returns the new array. 

Syntax:

string.split(separator, limit)

Example: This example implements the same functionality but with a different approach. It first takes the parameter portion of the URL and then uses the replace() method to form an object.

Javascript




console.log(search);
search = search.split('?')[1];
 
function GFG_Fun() {
    console.log('{"' + search.replace(/&/g, '", "')
        .replace(/=/g, '":"') + '"}',
        function (key, value) {
            return key === "" ? value : decodeURIComponent(value)
        });
}
GFG_Fun()


Output

https://www.w3wiki.org/?param_1=val_1&x=7&y=9
{"param_1":"val_1", "x":"7", "y":"9"} [Function (anonymous)]



Convert URL parameters to a JavaScript Object

Given an URL with parameters, The task is to get those parameters and convert them to a JavaScript Object using javascript. we’re going to discuss a few techniques.

Below is the following method to convert URL parameters to a JavaScript Object:

  • Using replace() Method
  • Using split() Method
  • Using for …of loop

Similar Reads

Method 1: Using replace() Method

This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value....

Method 2: Using split() Method

...

Method 3: Using for …of loop

This method is used to split a string into an array of substrings and returns the new array....