-4

How to replace by using regular expression in JavaScript?

Input:

The is currency \2,501 and \245,870.

Output:

The is currency ¥2,501 and ¥245,870.
Biffen
  • 6,249
  • 6
  • 28
  • 36
Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131
  • 1
    Possible duplicate of [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – Biffen Sep 20 '18 at 10:26
  • `const str = 'The is currency \\2,501 and \\245,870.'; str.replace(/\\/, '¥')` – Nick Sep 20 '18 at 13:11
  • Thanking on StackOverflow is done by upvoting and by answer accepting. If you are satisfied with my answer below, please mark it as accepted on the left side from my answer and / or upvote it. – Bharata Sep 26 '18 at 07:57
  • @Bharata, Input sting is `The is currency \2,501 and \245,870.` . it is not `\\\`. Another thing is, the string might be xxxx\bbb \1245.. So, output should be xxxx\bbb ¥1254. – Zaw Than oo Sep 27 '18 at 02:11
  • if you write `"\2"` then it will be converted to only ONE single character. It is not `2` anymore. This is JS! May be in another programming language you can write so, but not in JS. You can check it with: `var str = "currency \2,501"; alert(str.indexOf('2')); alert(str.indexOf('\\'));` In both alert-boxes you will get -1 what means "Nothing was found". I need answers: for two questions: **1.** Why you can not write `"currency \\2,501"` or may be `"currency |2,501"`? **2.** Is after this backsash all the time only `2` like `"\2..."` or may be it can be `"\5..."` or even `"\-2..."`? – Bharata Sep 27 '18 at 09:32
  • **Very important information:** your question with my answer will be deleted **tomorrow** from system – see here: https://meta.stackexchange.com/a/5222 If you accept my answer then it can not be deleted. Please do it and I will answer your question later. I need answers for two questions – see my previous comment.. – Bharata Sep 28 '18 at 06:09

1 Answers1

0

The backslash tries to escape the following character. For instance, \n is a newline character.

In your case you can not find backslash in your string because you tries to escape the following "2" character. In this case you have to write two backslashes to escape one backslash like follows:

var str = 'The is currency \\2,501 and \\245,870.';
console.log(str.replace(/\\/g, '¥')); //you get it here like ¥ because HTML is already loaded

//or like follows:
var yen = document.querySelector('div').innerHTML;
console.log(str.replace(/\\/g, yen));

//or direct like follows:
console.log(str.replace(/\\/g, '¥'));
<div>&yen;</div>
Bharata
  • 13,509
  • 6
  • 36
  • 50