-3

I have a string that contains String q = "What's the value of √32 and √83?";, my problem is replacing √num with sqrt(32) and sqrt(83).

That means my string should output:

What's the value of sqrt(32) and sqrt(83)

Actually, one question for me was answered in Java:

Replace all √num from a string java

When I try to do the same in JS, it's not changed:

  • 3
    You need a regex literal: `.replace(/√(\d+)\b/g, "sqrt($1)")` – trincot May 05 '21 at 10:51
  • Yes, I know, but regex should have worked? – Alien tackers May 05 '21 at 10:51
  • Okay, will try... – Alien tackers May 05 '21 at 10:51
  • thanks worked, why did you vote negative :/ – Alien tackers May 05 '21 at 10:52
  • Does this answer your question? [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – thedude May 05 '21 at 10:54
  • nope, its not mine – Alien tackers May 05 '21 at 10:55
  • 1
    I didn't downvote, but reading only a tiny bit about regular expressions in JavaScript would have given you the hint that you should use a regex literal, not a string (although that is also possible, but then you need to call the RegExp constructor). We appreciate when people do their research. – trincot May 05 '21 at 10:55
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) -> _"**DO NOT post images of code, data, error messages, etc.** - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text."_ – Andreas May 05 '21 at 10:56
  • Why should they work? The regular expression doesn't match anything in those strings. – Andreas May 05 '21 at 10:58

1 Answers1

2

This should help

"What's the value of √32 and √83".replaceAll( /√(\d+)/g ,"sqrt($1)");

matches the word with √ in the beginning. It can be accessed with $&

(\d+) matches digits inside previously matched string. It can be accessed with $1

/g to match all the occurrences