Open In App

How to remove portion of a string after certain character in JavaScript ?

Given a URL and the task is to remove a portion of URL after a certain character using JavaScript.

string.split(separator, limit)
string.substring(start, end)

Example 1: This example uses the substring() method to remove the portion of the string after certain character (?). 






<!DOCTYPE HTML>
<html>
    <head>
        <title>
            Remove portion of string after
            certain characters
        </title>
    </head>
     
    <body style = "text-align:center;">
     
        <h1 style = "color:green;" >
            GeeksForGeeks
        </h1>
 
        <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;">
        </p>
         
        <button onclick = "GFG_click()">
            click to remove
        </button>
         
        <p id = "GFG_DOWN" style =
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
         
        <script>
            var el_up = document.getElementById("GFG_UP");
            var el_down = document.getElementById("GFG_DOWN");
            var s = '/path/action?id=11612&value=44944';
            el_up.innerHTML = s;        
             
            function GFG_click() {
                s = s.substring(0, s.indexOf('?'));
                el_down.innerHTML = "String = "+s;
            }        
        </script>
    </body>
</html>                   

Output:

Example 2: This example uses the split() method to remove the portion of the string after certain character (?). 






<!DOCTYPE HTML>
<html>
    <head>
        <title>
            Remove portion of string after
            certain character
        </title>
    </head>
     
    <body style = "text-align:center;">
        <h1 style = "color:green;" >
            GeeksForGeeks
        </h1>
 
        <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;">
        </p>
         
        <button onclick = "GFG_click()">
            click to remove
        </button>
         
        <p id = "GFG_DOWN" style =
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
         
        <script>
            var el_up = document.getElementById("GFG_UP");
            var el_down = document.getElementById("GFG_DOWN");
            var s = '/path/action?id=11612&value=44944';
            el_up.innerHTML = s;        
             
            function GFG_click() {
                s = s.split('?')[0]
                el_down.innerHTML = "String = " + s;
            }        
        </script>
    </body>
</html>                   

Output:


Article Tags :