A-312 / jquery.caret.js

Position du curseur
0 stars 1 forks source link

replaceWorld(string, true) s'applique 2 fois #2

Open A-312 opened 5 years ago

A-312 commented 5 years ago

s'applique 2 fois

A-312 commented 5 years ago

https://jsfiddle.net/A_312/5m62tgoj/44/

function print() {
  var p = document.createElement("p"),
    html = Array.prototype.join.call(arguments, ", ");
  p.innerHTML = html;
  document.getElementById("console").appendChild(p);
  return p;
}

function zero(a) {
  return (a <= 9) ? "0" + a : "" + a;
}

function getWord(text, pos, c) {
  if (text[pos - 1] === " ") return null;
  for (var i = 0, length = 0, a = 0, match = [], t = (text || "").split(" "); i < t.length; i++) {
    length += a = 1 + t[i].length;
    if (pos <= length) {
      match = (t[i].replace(/\s+/g, "") !== "") ? [text.substr(0, length - a), t[i]] : null;
      return (c || !match) ? match : match[1];
    }
  }
}

function replaceWord(text, i, replace) {
  var match = getWord(text, i, true);
  if (!match) return text;
  return match[0] + text.substr(match[0].length).replace(match[1], replace);
}

const text = "Hello      ! I <b>must</b> to get a word in this sentence a",
          textplain = "Hello      ! I must to get a word in this sentence a";

for (let i = 0, $p, word, caret, line; i <= textplain.length; i++) { // noprotect
  $p = $("<p></p>").appendTo("#console");
  $p.append("text = \"<span class=str contenteditable=true></span>\";");
  $p.find(".str").html(text);
  $p.find(".str").caret(i);
  caret = $p.find(".str").caret();
  caret.replaceWord("<u>" + word + "</u>", true);

  line = print("<span class=number>" + zero(caret.start) + "; </span>" +
    "<span class=cmt>// " + Array(caret.start + 1).join(" ") + " <b>v</b>" +
    ((word !== null) ? " -- " + caret.word : "") + "</span>")

  $(line).after($p);

  for (let j=0;j<caret.three.length;j++)
    caret.three[j] = caret.three[j].tagName+"."+caret.three[j].className;
  $p = $("<p></p>")
    .text(JSON.stringify(caret, 0, 2))
    .appendTo("#console");

  word = getWord(textplain, i);
  print("text = <span class=str>\"" + replaceWord(textplain, i, "<u>" + word + "</u>") + "\"</span>;");
  print("<span class=number>" + zero(i) + "; </span>" +
    "<span class=cmt>// " + Array(i + 1).join(" ") + " <b>^</b>" +
    ((word !== null) ? " -- " + word : "") + "</span>");

  print(" ");
}