-1

I have a string called completionBar which contains this:

let completionBar = `〚⬛⬛⬛⬛⬛〛`;

I'm trying to replace a single ⬛ with ⬜, so I tried:

completionBar.replace(/\U+2B1B/, 'U+2B1C');

but nothing happen, what I did wrong?

2
  • 1
    The problem is that the + sign has a special meaning for the regex engine, Commented Jul 11, 2020 at 9:54
  • Doing this using the unicode encodings would be: completionBar.replace(/\u2B1B/, String.fromCharCode("0x2B1C")) Commented Jul 11, 2020 at 10:13

2 Answers 2

0

You can use /⬛/g in .replace().

I would try as the following if you want to replace all:

let completionBar = `〚⬛⬛⬛⬛⬛〛`;

const result  = completionBar.replace(/⬛/g, '⬜');

console.log(result)

If you need only the first to replace:

let completionBar = `〚⬛⬛⬛⬛⬛〛`;

const result  = completionBar.replace('⬛', '⬜');

console.log(result)

I hope this helps!

Sign up to request clarification or add additional context in comments.

4 Comments

oh really nice! how can I replace just one emojy?
@sfarzoso Just extended my answer with that.
thanks! just last question: it is possible replace the last emojy of the string?
You can get the last index with lastIndexOf() then using the answer's solution from here: How do I replace a character at a particular index in JavaScript?.
0

In my opinion, you can use escape and unescape function to show exactly the string code. It easy to debug and maintain the code.

let completionBar = `〚⬛⬛⬛⬛⬛〛`;

let escapeCompletionBar = escape(completionBar).replace(/u2B1B/g, 'u2B1C');

let result = unescape(escapeCompletionBar);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.