How to replace before first forward slash - JavaScript?


Let’s say the following is our string with forward slash −

var queryStringValue = "welcome/name/john/age/32"

To replace before first forward slash, use replace() along with regular expressions.

Example

Following is the code −

var regularExpression = /^[^/]+/
var queryStringValue = "welcome/name/john/age/32"
var replacedValue = queryStringValue.replace(regularExpression, 'index');
console.log("Original value="+queryStringValue);
console.log("After replacing the value="+replacedValue);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo245.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo245.js
Original value=welcome/name/john/age/32
After replacing the value=index/name/john/age/32

Updated on: 03-Oct-2020

603 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements