How to wrap part of a text in a node with JavaScript

后端 未结 5 1343
-上瘾入骨i
-上瘾入骨i 2020-11-28 23:36

I have a challenging problem to solve. I\'m working on a script which takes a regex as an input. This script then finds all matches for this regex in a document and wraps ea

5条回答
  •  无人及你
    2020-11-29 00:19

    As everyone has already said, this is more of an academic question since this shouldn't really be the way you do it. That being said, it seemed like fun so here's one approach.

    EDIT: I think I got the gist of it now.

    function myReplace(str) {
      myRegexp = /((^<[^>*]>)+|([^<>\.]*|(<[^\/>]*>[^<>\.]+<\/[^>]*>)+)*[^<>\.]*\.\s*|<[^>]*>|[^\.<>]+\.*\s*)/g; 
      arr = str.match(myRegexp);
      var out = "";
      for (i in arr) {
    var node = arr[i];
    if (node.indexOf("<")===0) out += node;
    else out += ""+node+""; // Here is where you would run whichever 
                                         // regex you want to match by
      }
      document.write(out.replace(//g, ">")+"
    "); console.log(out); } myReplace('

    This program is not stable yet. Do not use this in production yet.

    '); myReplace('

    This is a sentence.

    '); myReplace('

    This is a another and more complex even super complex sentence.

    '); myReplace('

    This is a a sentence. Followed by another one.

    '); myReplace('

    This is a an even more complex sentence.

    '); /* Will output:

    This program is not stable yet. Do not use this in production yet.

    This is a sentence.

    This is a another and more complex even super complex sentence.

    This is a a sentence. Followed by another one.

    This is a an even more complex sentence.

    */

提交回复
热议问题