How to reverse a string that contains the emoji in js All In One
How to reverse a string that contains the emoji in js All In One
如何在 js 中反转包含表情符号的字符串
question
emoji & unicode
const str = 'Hello world👩🦰👩👩👦👦'
// wanted ❓
// '👩👩👦👦👩🦰dlrow olleH'
Solutions
- loadsh
function reverse(txt) {
return _.split(txt, '').reverse().join('');
}
const text = 'Hello world👩🦰👩👩👦👦';
console.log(reverse(text));
// '👩👩👦👦👩🦰dlrow olleH'
https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js
- i18n API
Intl.Segmenter
(() => {
const text = 'Hello world👩🦰👩👩👦👦';
const result = [...new Intl.Segmenter().segment(text)].map(x => x.segment).reverse().join('');
console.log(`result =`, result)
// '👩👩👦👦👩🦰dlrow olleH'
})()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter
- js &
unicode
String.prototype.reverse = function() {
let textArray = [...this];
let reverseString = "";
for (let i = 0; i < textArray.length; i++) {
let emojis = textArray[i];
// ❓组合 emoji, 不太好理解
while (textArray[i + 1] === '\u200d') {
emojis += textArray[i + 1] + textArray[i + 2];
i = i + 2;
}
reverseString = emojis + reverseString;
}
return reverseString;
}
const text = "Hello world👩🦰👩👩👦👦";
console.log(text.reverse());
DOM
API
const str = 'Hello world👩🦰👩👩👦👦'
document.createTextNode('\u202e' + str)
"‮Hello world👩‍🦰👩‍👩‍👦‍👦"
document.createTextNode(str)
"Hello world👩‍🦰👩‍👩‍👦‍👦"
借助于浏览器可以自动识别组合 emoji 的功能,有局限性
const text = 'Hello world👩🦰👩👩👦👦'
let original = document.getElementById('original')
original.appendChild(document.createTextNode(text))
let result = document.getElementById('result')
result.appendChild(document.createTextNode('\u202e' + text))
- regex ❓潜在 bug
const text = 'Hello world👩🦰👩👩👦👦';
const reversed = text.match(/.(\u200d.)*/gu).reverse().join('');
console.log(reversed);
const text = 'Hello world👩🦰👩👩👦👦';
const reversed = text.match(/.(\u200d.)*/gu).reverse().join('');
console.log(reversed);
https://regexper.com/#%2F.(\u200d.)*%2Fgu
demos
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
Zero Width Joiner / 零宽连接器
零宽字符
/Zero Width Space
U+200D
Zero width joiner
<ZWJ>
Placed between characters that would not normally be connected in order to cause the characters to be rendered using their connected form in certain languages.
Man] [ZWJ] [Woman] [ZWJ] [Boy]
=> 👨👩👦
=> Family: Man, Woman, Boy
https://en.wikipedia.org/wiki/Zero-width_joiner
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17666225.html
未经授权禁止转载,违者必究!