-2

How to get regex with replace method? In my case I've got string which uses char / between.

input:

var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem + "/mc/" + mainCategory + "/sc/" + subCategory + "/ty/" + type;

output:

"cn/Nemesis Group/st/2/ic/null/pr/1 - High/es/null/mc/Add/Button/sc/Core/Label/ty/str"

variable mainCategory and subCategory returns string 'Add/Button' and 'Core/Label'

How to replace 'Add/Button' to 'Add%2FButton' and 'Core/Label' to 'Core%2FLabel' without changing any other char?

string.replace("\/", "%2F") 

will change all char / to %2F

miroabyss
  • 1
  • 3

2 Answers2

1

You can use encodeURIComponent() and decodeURIComponent() to transform this String

Example:

const companyName = "Company",
  state = "State",
  incCi = "IncCi",
  priority = "Priority",
  emplSystem = "EmplSystem",
  mainCategory = 'Add/Button',
  subCategory = 'Core/Label',
  type = "Type";

var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem +
  "/mc/" + encodeURIComponent(mainCategory) +
  "/sc/" + encodeURIComponent(subCategory) + "/ty/" + type;

console.log(string)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nils Schwebel
  • 641
  • 4
  • 14
0

It sounds to me like you are looking to encode the url. You can use encodeURI in JS to encode a url.

let encodedURL = encodeURI(url);

You can read more about it here.

If you want to encode the string altogether without ignoring any domain related parts, you can us encodeURIComponent()

let encodedURL = encodeURIComponent(url);

You can read more about their differences here.

EDIT:

If you are not encoding a url and you just want to repalce / with %2F only in mainCategory and subCategory then you need to run the regex on the string itself before joining them.

var string = "cn/" + companyName + 
    "/st/" + state + 
    "/ic/" + incCi + 
    "/pr/" + priority + 
    "/es/" + emplSystem + 
    "/mc/" + mainCategory.replace("\/", "%2F")  +
     "/sc/" + subCategory.replace("\/", "%2F")  + 
    "/ty/" + type;
kks21199
  • 1,116
  • 2
  • 10
  • 29