1

In postman, I want to change all occurrences of a slash to an underscore in my string.

So far I have written a test which parses the JSON response and pushes the string I want into an array, from this point my code looks like below

//an example string is below

var string =  "1/7842/0889#001";

// convert / to _
var slash = "/";
var newstring = string.replace (slash, "_");


// This just changes the first occurrence of the slash to an underscore

I tried using the `g' modifier and this fails in Postman

var newstring = string.replace (/slash/g, "_");

I want the string to end up as

"1_7842_0889#001";

Danny Dainton
  • 23,069
  • 6
  • 67
  • 80
Nick Pilbeam
  • 23
  • 2
  • 6
  • Just use `string.replace(/\//g, '_')` and refer the original question [here](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string). – M0nst3R Jul 24 '19 at 09:09

3 Answers3

3

You need to escape / in your regexp with '\'

//an example string is below
var string =  "1/7842/0889#001";

// convert / to _
var newstring = string.replace (/\//g, "_"); // prints 1_7842_0889#001

console.log(newstring);
klugjo
  • 19,422
  • 8
  • 57
  • 75
0

Split it with forward slash and join them with _

var string =  "1/7842/0889#001";

var strArray = string.split('/');

var newString = strArray.join("_");

Or in one line

var newString = string.split('/').join("_");
Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
0
User regular expression which will help  us to replace the characters globally by adding g

All regular expressions will reside inside // So for your question the following code will help

Str.replace(/\//, "_")

Added \/ just to escape it's value
ajaykumar mp
  • 487
  • 5
  • 12