javascript - Postman - changing all occurrences of a character in a string - Stack Overflow

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

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";

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";

Share Improve this question edited Jul 24, 2019 at 9:06 Danny Dainton 26k6 gold badges74 silver badges88 bronze badges asked Jul 24, 2019 at 8:54 Nick PilbeamNick Pilbeam 231 gold badge2 silver badges7 bronze badges 1
  • Just use string.replace(/\//g, '_') and refer the original question here. – M0nst3R Commented Jul 24, 2019 at 9:09
Add a ment  | 

3 Answers 3

Reset to default 4

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);

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("_");
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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744347723a4569788.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信