文本框中的前缀/后缀突出显示的文本

时间:2014-05-01 11:41:04

标签: javascript

我必须创建一个小的javascript函数,为文本框中的选定文本添加前缀和后缀。

这是我到目前为止所做的:

function AddTags(name, prefix, suffix) {
    try
    {
        var textArea = document.getElementById(name).value;
        var i = 0;
        var textArray = textArea.split("\n");
        if (textArray == null) {
            document.getElementById(name).value += prefix + suffix
        }
        else {
            for (i = 0; i < textArray.length; i++) {
                textArray[i] = prefix + textArray[i] + suffix;
            }
            document.getElementById(name).value = textArray.join("\n");
        }
    }
    catch (err) { }
}

现在,此函数会为每行添加提供的前缀和后缀,但我需要了解如何在Text before selectionSelected text和{{1}中分解文本框中的文本}。

有人对此有任何经验吗?

修改 TriniBoy的功能让我走上正轨。我不需要整个建议。 这是我原始代码的编辑版本:

Text after selection

Thx TriniBoy,我将你的提升标记为答案。

1 个答案:

答案 0 :(得分:2)

根据您的演示和解释,希望我的要求正确无误。

请参阅代码注释以了解故障。

See demo fiddle here

var PreSuffApp = PreSuffApp || {
selText: "",
selStart: 0,
selEnd: 0,
getSelectedText: function (id) {
    var text = "",
        docSel = document.selection, //For IE
        winSel = window.getSelection,
        P = PreSuffApp,
        textArea = document.getElementById(id);

    if (typeof winSel !== "undefined") {
        text = winSel().toString(); //Grab the current selected text
        if (typeof docSel !== "undefined" && docSel.type === "Text") {
            text = docSel.createRange().text; //Grab the current selected text
        }
    }
    P.selStart = textArea.selectionStart; //Get the start of the selection range
    P.selEnd = textArea.selectionEnd; //Get the end of the selection range
    P.selText = text; //Set the value of the current selected text
},

addTags: function (id, prefix, suffix) {
    try {
        var textArea = document.getElementById(id),
            P = PreSuffApp,
            range = P.selEnd - P.selStart; //Used to calculate the lenght of the selection

        //Check to see if some valuable text is selected
        if (P.selText.trim() !== "") {
            textArea.value = textArea.value.splice(P.selStart, range, prefix + P.selText + suffix); //Call the splice method on your text area value
        } else {
            alert("You've selected a bunch of nothingness");
        }
    } catch (err) {}
}
};

//Extend the string obj to splice the string from a start character index to an end range, like an array.
String.prototype.splice = function (index, rem, s) {
    return (this.slice(0, index) + s + this.slice(index + Math.abs(rem)));
};