-2

(this question is the continuation of my previous question : "how to find private char utf8 in a text?") I need to replace each match with its value (which is stored in a map) but I have tested several things, including this one (below) but it does not work. I probably don’t have the hindsight to find the solution. I’ve been on for an hour. I probably did a big mistake sorry for that. Here's my code:

const regex = /[\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;

var map = new Map();
//set example values in the map
map.set("󰀁", 'something1'); 
map.set("󰀂", 'something2');
map.set("󰀃", 'something3');
map.set("󰀄", 'something4');
    
const str = "\u{f0001} lorem ipsum \u{f0002} dolor sit amet \u{f0003}\n consectetur adipiscing elit\u{f0004}\sed do eiusmod tempor</"; // my text
console.log(str);
    
var tab = str.match(regex).map(x => Array.from(x)
    .map((v) => v.codePointAt(0).toString(10))
    .map((hex) => "0000".substring(0, 4 - hex.length) + hex))
    
for(var i = 0 ; i < tab.length ; i++){
    str.replace(/[\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u, map.get("&#"+tab[i][0]+";"));
}
console.log(str); //nothing change
Tim
  • 5,435
  • 7
  • 42
  • 62
Esposito
  • 9
  • 6
  • Strings are immutable, you modify the `str` with `replace`, but do not assign the new value to it. But you also need to declare `str` with *`let`*, not with *`const`* – Wiktor Stribiżew Jul 01 '20 at 15:50

1 Answers1

-1

strings are immutable, no method or operators will change them.

in your for loop you should reassign str to the result of str.replace, I think that's all

for(var i = 0 ; i < tab.length ; i++){
    str = str.replace(/[\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u, map.get("&#"+tab[i][0]+";"));
}

note that you don't have the 'g' flag on this regex, not sure if this is intended

Edit: as Wiktor pointed out, you will have to switch your declaration from const to let

Apolo
  • 3,844
  • 1
  • 21
  • 51