1

I want to replace ^ to ** in js but we try to use str.replace it only replaces a first one and rest string are same

 const input = "2^3+4^4";
    const replace = input.replace("^", "**");
    console.log(replace);

output :

2**3+4^4

but i want

2**3+4**4
sabban
  • 131
  • 5

5 Answers5

3

You can use regex like this:

const input = "2^3+4^4";
const replace = input.replace(/\^/g, "**");
console.log(replace);
Jop Knoppers
  • 676
  • 1
  • 10
  • 22
3

You can use regex with flag g which make the regex don't stop to the first occurrence.

const input = '2^3+4^4';

const replace = input.replace(/\^/g, '**');

console.log(replace); // output: 2**3+4**4
8HoLoN
  • 1,122
  • 5
  • 14
Eldynn
  • 183
  • 10
0

const replace = input.replace(/^/g, "**");

  • Won't work, this will simply prepend "**" to any given string. Besides that, please, make a minimal snippet or at least mark your code as code. – Thomas Jul 25 '20 at 09:01
0

Try this:

const input = "2^3+4^4";
const replace = input.replace(/\^/g, "**");
console.log(replace);

The /g means it's "global" replacement.

Daniser
  • 162
  • 4
0

const replace = input.split("^").join("**")

Indrakant
  • 361
  • 3
  • 9