0

我正在尝试创建一个非常简单的wysiwyg编辑器(没有颜色),并且我尝试为一个开始标签创建“结束标签”。

我知道当我使用 value 时它不起作用,因为它获得了 the 的全部值,textarea所以我尝试使用stringusing indexOfand replace

但似乎代码不起作用,我研究过在中搜索pirticular关键字(假设它<html>textarea并将其替换为另一个(关键字<html> </html>:)

JavaScript

$(document).ready(function() {
    var textarea = document.getElementById('codeTextarea');
    textarea.keyup(function(e) {
        var str = textarea.value;
        if(str.indexOf('<html>') != -1){
            str.replace("<html>", "<html> </html>");
        }
    });
});

HTML

<textarea id="codeTextarea"></textarea>

如何textarea用另一个字符串替换 a 中的特定字符串?(即:<html>将替换为<html> </html>

注意

请不要告诉我使用价值,因为价值可以<doctype> <html>,然后想要的代码将不起作用。

4

2 回答 2

1

There are several mistakes in your code. The first one is that you are using jquery .keyup event which is missing in the normal DOM object. The second problem is that .replace actually returns the result of the replacement. And the third one is that you didn't apply the value to the text area.

var textarea = $('#codeTextarea');
textarea.keyup(function(e) {
    var field = $(this);
    var str = field.val();
    if(str.indexOf('<html>') != -1){
        str = str.replace("<html>", "<html> </html>");
    }
    field.val(str);
});

However, this code works, but you should rethink using regular expressions. Because once you convert the <html> to <html></html> next time you will get <html></html></html> and so on and so on.

Here is a jsfiddle http://jsfiddle.net/ErF4k/1/

And here is another jsfiddle http://jsfiddle.net/ErF4k/3/ which uses regex. That's not my strongest part, but the idea is to match <html> followed by something different then a tag.

var textarea = $('#codeTextarea');
textarea.keyup(function(e) {
    var field = $(this);
    var str = field.val();        
    if(str.indexOf('<html>') != -1){
        str = str.replace(/\<html\>([a-z|A-Z|0-9| ])/g, "<html></html>");
    }
    field.val(str);
});

Just start typing <html> and press a letter, number or interval.

于 2013-08-31T16:28:25.287 回答
0

完成替换字符串中的内容后,您会忘记设置 textarea 的值。尝试做:

$(document).ready(function() {
    var textarea = document.getElementById('codeTextarea');
    textarea.keyup(function(e) {
        var str = textarea.value;
        if(str.indexOf('<html>') != -1){
            textarea.value = str.replace("<html>", "<html> </html>");
        }
    });
});
于 2013-08-31T16:20:37.707 回答