Skip to content

Instantly share code, notes, and snippets.

@seanghay
Last active September 21, 2022 09:38
Show Gist options
  • Save seanghay/90774fa212025339c086d48f8381a159 to your computer and use it in GitHub Desktop.
Save seanghay/90774fa212025339c086d48f8381a159 to your computer and use it in GitHub Desktop.
Automatically insert ZWSP into text.
import MagicString from "magic-string";
/**
* Automatically insert ZWSP into text.
* @param {string} value
* @param {string | undefined} sep
* @returns {string}
*/
export function insertZeroWidthSpace(value, sep = '\u200b') {
const regex = /[\u1780-\u17ff]+/gm
const str = new MagicString(value);
const segmenter = new Intl.Segmenter('km', { granularity: "word" });
let result;
while (result = regex.exec(value)) {
const { index: start } = result;
const end = regex.lastIndex;
const text = result[0];
const iterator = segmenter.segment(text);
const segments = Array.from(iterator);
// skipped because cannot segment
if (segments.length <= 1) {
continue;
};
const parts = new MagicString('');
for (let i = 0; i < segments.length; i++) {
const { segment, isWordLike } = segments[i];
parts.append(segment);
const nextSegment = segments[i + 1]
if (isWordLike && nextSegment && nextSegment.isWordLike) {
if (nextSegment.segment.length > 1) {
parts.append(sep);
}
}
}
str.overwrite(start, end, parts.toString());
}
return str.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment