I am trying to make a small node application that lets me convert text to double-struck "letters". I am fairly new to JavaScript, and I was wondering what the best way to do this?
I could use: string.replace("A", doublestruck.uppercase.A) (see below) 62 (26 uppercase, 26 lowercase, 10 number), but I feel like there is definitely a better way to do this.
// specialcharacters.js
const doubleStruckUpper = {
A: "𝔸", B: "𝔹", C: "ℂ", D: "𝔻", E: "𝔼",
F: "𝔽", G: "𝔾", H: "ℍ", I: "𝕀", J: "𝕁",
K: "𝕂", L: "𝕃", M: "𝕄", N: "ℕ", O: "𝕆",
P: "ℙ", Q: "ℚ", R: "ℝ", S: "𝕊", T: "𝕋",
U: "𝕌", V: "𝕍", W: "𝕎", X: "𝕏", Y: "𝕐",
Z: "ℤ"
};
const doubleStruckLower = { ... };
const doubleStruckNumbers = { ... };
module.exports.doubleStruck = {
uppercase: doubleStruckUpper,
lowercase: doubleStruckLower,
numbers: doubleStruckNumbers,
};
// index.js
const { doubleStruck } = require("./specialcharacters");
var string = "Change this to double-struck characters";
string
.replace("A", doubleStruck.uppercase.A)
.replace("B", doubleStruck.uppercase.B)
// and so on
This would work, but it would have to be so long and there is probably a better way to do this.
Thanks in advance!
.replace lets you use a function:
const doubleStruckUpper = {
A: "𝔸", B: "𝔹", C: "ℂ", D: "𝔻", E: "𝔼",
F: "𝔽", G: "𝔾", H: "ℍ", I: "𝕀", J: "𝕁",
K: "𝕂", L: "𝕃", M: "𝕄", N: "ℕ", O: "𝕆",
P: "ℙ", Q: "ℚ", R: "ℝ", S: "𝕊", T: "𝕋",
U: "𝕌", V: "𝕍", W: "𝕎", X: "𝕏", Y: "𝕐",
Z: "ℤ"
};
var string = "CHANGE THIS TO DOUBLE STRUCK LETTERS";
var result = string.replace(/[A-Z]/g, matchedLetter => doubleStruckUpper[matchedLetter]);
console.log(result);
Combined with a regex, you can find and match all desired characters and replace them, one by one, with the desired character. Since you've already created character maps, this should be a fairly fast and easy process, though I would recommend combining your character maps into a single map to make it faster and simpler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With