Javascript: 包含特殊字符的文本选择

Javascript: text selection including special characters

我正在使用这个 javascript 代码来获取插入符号前的单词:

sel = window.getSelection()
var selectedRange = sel.getRangeAt(0);
sel.collapseToStart();
sel.modify("move", "backward", "word");
sel.modify("extend", "forward", "word");

这会得到单词,即使没有尾随空格(例如 "word"),但会省略单词末尾的特殊字符(例如 "word:" 得到 "word").

如果我在单词中包含冒号,例如 "wo:rd",这会得到所有 5 个字符。

不过,我确实需要尾随特殊字符。我该怎么做?

我明白了,对于示例代码的草率,我深表歉意,但它是:jsFiddle

var i = 0;

function getBeforeSelection() {
    var sel = window.getSelection(),
        selectedRange = sel.getRangeAt(0),
        sel2,
        res,
        finalValue,
        regexObj;

    sel.collapseToStart();
    sel.modify("move", "backward", "word");
    sel.modify("extend", "forward", "word");

    finalValue = sel.toString();

    regexObj = new RegExp(finalValue + '[^A-Za-z0-9\s\b]*');

    res = sel.focusNode.nodeValue.trim().match(regexObj);

    alert(res);

}

// added for sake of example, calls getBeforeSelection on double click 
// (when selection is made)
document.addEventListener('click', function (e) {
    i++;

    if (i > 1) {
        getBeforeSelection();
        i = 0;
    } 
});