0

Within an Extendscript Regex search in an InDesign document, it seems that I can't use the "+" operator to concatenate the "\u" and and 4-digit Unicode value. Example:

var text = abcabcabc;
var re = new RegExp("\u0061", "g");
text = text.replace(re, "X");

will bring XbcXbcXbc as expected, but

var text = abcabcabc;
var u = "0061";
var re = new RegExp("\u" + u, "g");
text = text.replace(re, "X");

will bring \u0061bc\u0061bc\u0061bc.

So what's wrong here? Is it the + operator that doesn't work at this point? Is there any other possibility to concatenate the two components so that they are recognized as a complete Unicode value? Any advise is highly appreciated.

InSync
  • 4,851
  • 4
  • 8
  • 30
Rudi
  • 61
  • 1
  • 9
  • 2
    You need to escape the backslash: `"\\u" + u`. – InSync Aug 14 '23 at 12:32
  • That actually brings \u0061bc... as well. The crazy thing is that the concatenation works well in the search string but not in the replace string. – Rudi Aug 14 '23 at 14:40
  • 1
    Sounds like you used this in a normal string. I thought you want a `RegExp`? If it's a real character you want, use `String.fromCharCode(parseInt(a, 16))` or `String.fromCharCode('0x' + a)`(I'm not sure if this is ECMAScript3 compliant/available in ExtendScript though). – InSync Aug 14 '23 at 15:36
  • 1
    Both solutions work well ... thanks a lot! – Rudi Aug 14 '23 at 15:57
  • Just for completeness, this is a duplicate of [Hex Number to Char using Javascript](https://stackoverflow.com/q/40977000). To 3000+-rep users: Please vote to close. To other users: Always flag as duplicate instead of answering a dup. – InSync Aug 15 '23 at 16:36

2 Answers2

1

The correct answer has been contributed by InSync: To be version- and OS-independant you'd use

String.fromCharCode(parseInt(a, 16));

or

String.fromCharCode('0x' + a);

to concatenate the replace string for a RegExp operation using Adobe InDesign scripting (ExtendScript).

Rudi
  • 61
  • 1
  • 9
0

The solution from the first comment works just fine for me (InDesign CC 2023, macOS):

var text = 'abcabcabc';
var u = '0061';
var re = new RegExp( "\\u" + u, "g");
text = text.replace(re, "X");

$.writeln(text);
alert(text);

Result:

XbcXbcXbc

enter image description here

Update

I just tired it on Win7 InDesign CS6 and it works fine as well:

enter image description here

Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23
  • You are abviously on MAC; I'm working on Windows. Very interesting to see the difference - after all, there seem to be slight differences. Thanks a lot for trying! – Rudi Aug 15 '23 at 04:35
  • I just tired it on Win7 InDesign CS6 and it works fine as well – Yuri Khristich Aug 15 '23 at 06:15
  • 1
    Again a difference - 32bit InDesign (CS6) vs. 64bit InDesign (CC2023) where some things in fact seem to work different (not only this one). Anyway - problem solved which is great. – Rudi Aug 15 '23 at 07:26