假设我把这3个表情符号串在一个字符串中:
除了字符串中的表情符号外,没有任何空格或任何其他字符。
如何删除javascript中的最后一个表情符号?
发布于 2017-10-24 12:32:55
好的,下面是我解决这个问题的方法:
function deleteEmoji(emojiStr) {
let emojisArray = emojiStr.match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g);
emojisArray = emojisArray.splice(0, emojisArray.length - 1);
return emojisArray.join("");
}
let emojitext = "";
console.log(deleteEmoji(emojitext));发布于 2020-10-24 12:01:11
下面的答案没有使用任何特殊的包,并且安全地删除了最后一个表情符号
function safeEmojiBackspace(str)
{
let initialRealCount = fancyCount(str);
while(str.length > 0 && fancyCount(str) !== initialRealCount - 1)
{
str = str.substring(0,str.length - 1);
}
return str;
}
function fancyCount(str){
const joiner = "\u{200D}";
const split = str.split(joiner);
let count = 0;
for(const s of split){
//removing the variation selectors
const num = Array.from(s.split(/[\ufe00-\ufe0f]/).join("")).length;
count += num;
}
//assuming the joiners are used appropriately
return count / split.length;
}样本使用
let str = "something";
str = safeEmojiBackspace(str);//"something"发布于 2017-10-24 11:55:49
你可以做到这一点。它将永远移除最后的表情符号。
function removeEmoji() {
var emoStringArray = document.getElementById('emoji').innerHTML;
var lastIndex = emoStringArray.lastIndexOf(" ");
var stripedEmoStringArray = emoStringArray.substring(0, lastIndex);
document.getElementById('emoji').innerHTML = stripedEmoStringArray;
}<p id="emoji">
</p>
<button onclick="removeEmoji()">Remove</button>
https://stackoverflow.com/questions/46909766
复制相似问题