0

I have a url parameter that needs to be encoded in a very specific way.

Spaces should be converted to %20

Backslash should be converted to %5C

Forward slash should be converted to %2F

How would I do this in javascript?

input:

var before_encode = 'MS EXCEL \ MACRO/AUTOMATION'

expected output:

var after_encode = 'MS%20EXCEL%20%5C%20MACRO%2FAUTOMATION'

The var after_encode will then be fed to a json get request and only works if encoded this way. Any help would be greatly appreciated as I am new to java script.

2
  • 1
    replace? str = str.replace(' ', '%20')? And for each letters Commented Mar 23, 2020 at 19:20
  • ahhh... maybe our own customer encoder? I think that will work! How would I do this with the forward slash and backslash though? Could you write an example of the syntax? Commented Mar 23, 2020 at 19:22

1 Answer 1

2

it's my decide:

const input = 'MS EXCEL \\ MACRO/AUTOMATION';
const output = input
  .replace(/ /g, "%20")
  .replace(/\\/g, "%5")
  .replace(/\//g, "%2F");

console.log(input);
console.log(output);

Backslash must be '\\', because '\' is a spec letter in programming

Sign up to request clarification or add additional context in comments.

3 Comments

one issue with this answer otherwise everything works great. I have a single backslash I am trying to change and not a double backslash like in your example. Can you please change the const input to 'MS EXCEL \ MACRO/AUTOMATION' like what I had in the question and update the answer accordingly?
how do I convert my \ into \\? The examples I have found online do not work.
@acodejdatam '\' - it's a special letter, this letter using with other letters, if u want use this letter for text - use double letter for get single letter, \\ => \, \\\\ => \\. Single backslash in code it's a special letter, but when u got this letter from other sources, u got as '\\', example: user write next string in input: "I like\love pizza", when you'll parse it in your code, you'ill get: text[i] === '\\' -> true when 'i' == 6 and u'll get error because '\' it's a special letter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.