2

I have replace the problem in react. I want ^ to 25%5E, but I just can replace one of ^ in the string, cannot replace all ^ symbol to 25%5E. Below is my sample code:

var urlStr = "http://localhost:3005/branch-management/edit-branch/?companyName=ABC%20SDN%20BHD%20!!!!%40%40%40%40%23%24%^%26*()&branchName=ABC%20!%40%23%24%^%26*()_";
var newUrlStr = urlStr.replace("^", "25%5E");

console.log(newUrlStr);

Error Result:

img

How to solve this problem?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Fatt Sky
  • 650
  • 3
  • 11

3 Answers3

4

You should use replaceAll which is for replacing all matched strings

var urlStr = "http://localhost:3005/branch-management/edit-branch/?companyName=ABC%20SDN%20BHD%20!!!!%40%40%40%40%23%24%^%26*()&branchName=ABC%20!%40%23%24%^%26*()_";
var newUrlStr = urlStr.replaceAll("^", "25%5E");

console.log(newUrlStr);

You also can use regex with /g (a global flag) to have similar behaviour

    var urlStr = "http://localhost:3005/branch-management/edit-branch/?companyName=ABC%20SDN%20BHD%20!!!!%40%40%40%40%23%24%^%26*()&branchName=ABC%20!%40%23%24%^%26*()_";
var newUrlStr = urlStr.replace(/\^/g, "25%5E");

console.log(newUrlStr);
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
1

use regex to find all occurence of ^ and replace.

var urlStr = "http://localhost:3005/branch-management/edit-branch/?companyName=ABC%20SDN%20BHD%20!!!!%40%40%40%40%23%24%^%26*()&branchName=ABC%20!%40%23%24%^%26*()_";
var newUrlStr = urlStr.replace(/\^/g, "25%5E");

console.log(newUrlStr);
Mohit Sharma
  • 622
  • 6
  • 11
0

Use the replaceAll() method

var urlStr = "http://localhost:3005/branch-management/edit-branch/?companyName=ABC%20SDN%20BHD%20!!!!%40%40%40%40%23%24%^%26*()&branchName=ABC%20!%40%23%24%^%26*()_";

var newUrlStr = urlStr.replaceAll("^", "25%5E");

console.log(newUrlStr);

the replace method either takes a pair of char's or a pair of CharSequence's (of which String is a subclass, so it'll happily take a pair of String's).

The replace method will replace all occurrences of a char or CharSequence. On the other hand, the first String arguments of replaceFirst and replaceAll are regular expressions (regex). Using the wrong function can lead to subtle bugs.

Shachar297
  • 599
  • 2
  • 7