div“内容可编辑": 获取和删除插入符号前的单词 [英] Div "contenteditable" : get and delete word preceding caret

查看:35
本文介绍了div“内容可编辑": 获取和删除插入符号前的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢这个问题和蒂姆发布的答案下来,我做了一个函数来获取contenteditable"div中插入符号前面的单词.

Thanks to this question and answer posted by Tim Down, I made a function to get the word preceding caret in a "contenteditable" div.

这是一个fiddle,函数如下:

function getWordPrecedingCaret (containerEl) {
    var preceding = "",
        sel,
        range,
        precedingRange;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            range = sel.getRangeAt(0).cloneRange();
            range.collapse(true);
            range.setStart(containerEl, 0);
            preceding = range.toString();
        }
    } else if ((sel = document.selection) && sel.type != "Control") {
        range = sel.createRange();
        precedingRange = range.duplicate();
        precedingRange.moveToElementText(containerEl);
        precedingRange.setEndPoint("EndToStart", range);
        preceding = precedingRange.text;
    }
    var lastWord = preceding.match(/(?:s|^)([S]+)$/i);
    if (lastWord) {
        return lastWord;
    } else {
        return false;
    }
}

我的问题:一旦得到最后一个字,我怎样才能将它从 div 中删除?请注意,我不想删除 div 中出现的任何单词,只删除插入符号之前的单词.

My question: Once gotten the last word, how can I remove it from the div? Note that I don't want to remove any occurrence of the word in the div, only occurrence preceding the caret.

提前谢谢你!

推荐答案

一个很好的解决方案,在插入符号之前获得单词

A nice solution to get the word before the caret

export function getWordBeforeCare() {
  const range = window.getSelection().getRangeAt(0);
  if (range.collapsed) {
    const text = range.startContainer.textContent.substring(
      0,
      range.startOffset + 1
    );
    return (
      text
        .split(/s/g) // if you want the last word until the space
        // .split(//g) //if you want the last word until a non caractere
        .pop()
        .trim()
    );
  }
  return "";
}

这篇关于div“内容可编辑": 获取和删除插入符号前的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆