如何替换字符串中的单词,如语法高亮?

时间:2016-03-04 14:25:45

标签: javascript

我试图重现语法突出显示的行为。

需要怎样工作?

当我写作时,他们需要查看文本以找到一些特定的单词并添加颜色。

所以,我已经尝试过了:

HTML:

<div id="text" contenteditable="true">O </ div>

JS:

var text = document.getElementById('text');

text.onkeyup = function(evt) {
  if (this.textContent.indexOf("Brasil") > 0) {
    text.innerHTML = this.textContent.replace("Brasil", "<b class='green'>Brasil<b>");
  }
};

CSS:

.green{
  color:green;
}

jsfiddle

上运行

问题:

1 - 光标移动到开始。

2 - 使用indexOf写入一个单词后,它们将始终替换为相同的数据。

3 个答案:

答案 0 :(得分:0)

您需要将光标设置回输入文本的末尾。有关如何执行此操作的详细信息,请参阅https://stackoverflow.com/a/512542/5448324

至于查找字符串中特定文本的所有实例,我引用您https://stackoverflow.com/a/3365999/5448324

答案 1 :(得分:0)

我根据您的代码创建了一个小提琴https://jsfiddle.net/d24z9ka4/ 它很糟糕,但它的工作原理:-),以下是:

text.onkeyup = function(evt) {
  // get how many times 'Brasil' occurs 
  var counter = this.textContent.split(/(Brasil)/ig).length;

  // lastCount is the place of the last occurrence, or nothing 
  if (counter > 1 && (!this.lastCount || this.lastCount < counter) ) {
    this.lastCount = counter;
    // get's all places where 'Brasil' is written
    this.innerHTML = this.textContent.replace(/(Brasil)/ig, "<b class='green'>Brasil</b>&nbsp;");

    // this moves cursor to last position available
    // based on this https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div
    var range = document.createRange();
    var sel = window.getSelection();

    // this is last node available, we'll go there
    var lastNode = text.childNodes.item(text.childNodes.length -1)
    range.setStart(lastNode, 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
  }
};

答案 2 :(得分:0)

您可以尝试以下操作:

&#13;
&#13;
var text = document.getElementById('text');
var closingTag = "</b>";

text.onkeyup = function(evt) {
  // replace the string
  this.innerHTML = this.textContent.replace(/Brasil/ig, '<b class="green">Brasil</b>');
  // add an empty text node to the contenteditable element
  // so that we can move the cursor to it
  this.appendChild(document.createTextNode(""));
  // moving the cursor at the end of the element
  setCaret();
};

function setCaret() {
  var el = document.getElementById("text");
  var range = document.createRange();
  var sel = window.getSelection();
  // get the last child node from the contenteditable element
  // it's an empty node, so set the offset to 0
  range.setStart(el.childNodes[el.childNodes.length - 1], 0);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
  el.focus();
}
&#13;
.green {
  color: green;
}
#text {
  border: 1px solid rgba(0,0,0,.2);
}
&#13;
<div id="text" contenteditable="true"></ div>
&#13;
&#13;
&#13;

setCaret功能来自Tim的answer

我不知道为什么,但是一旦你开始输入,代码的js部分将被打印到SO的片段中的div中。所以这里是JSFiddle