0

is there anyway to wrap textarea text with tags ? Javascript/Jquery

B = Bold I = Italic U = Underline S = Strike

For example:

-+-+-+-+-
 B I U S
-+-+-+-+-
<textarea>
 Some text here
</textarea>

When i highlight "here" and then click on bold its will be smth like this.

-+-+-+-+-
 B I U S
-+-+-+-+-
<textarea>
 Some text [b]here[/b]
</textarea>

Hope i will find solution and this is it thanks.

2 Answers 2

4

this is the solution

function wrapText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
Sign up to request clarification or add additional context in comments.

Comments

1

useage

console.log(parseBB('[b]hello [/b][u]world[/u]'));
console.log(parseBB(document.getElementById('textareaID').value));
console.log(parseBB($('#textareaID').val()));

test case

$('#output-container').html(parseBB($('#textareaID').val()));

..

function parseBB(string){
var _string = string.replace(/\n/g, '<br>'),
parseExp = new RegExp(/^(.*)\[(b|u|i|s)\]([A-Za-z0-9 ._-]+)\[\/[a-z]+\](.*)$/g);

(function run(){
    if(parseExp.test(_string)){
        _string = _string.replace(parseExp , '$1<$2>$3</$2>$4');
        run();
    }
})();
return _string;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.