javascript - 字母替换一个字符的麻烦

标签 javascript regex

这是以下问题的延续:customizable letter replacer

我有一个可以替换字母的代码,您可以为某个字母输入您想要的任何内容。例如,如果您想将“l”替换为“u”,则输入“hello”,输出将为“heuuo”。

当我希望用户能够选择要替换为任何字符串的任何字符串时,问题就出现了。例如,如果用户希望将“鸡”替换为“鸡 block ”。

问题是,我只能选择包含一个字母的字符串。我不能像上面的例子(鸡 block )那样做,但我可以用我想要的任意数量的字符替换任何一个字符。

请尝试解释发生了什么,而不仅仅是给我代码,谢谢!

// My globals
var output = $("#output");
var extra_customizing = $("#extra-customizing");

String.prototype.cap = function () { // needed or demonstration
    return this.charAt(0).toUpperCase() + this.slice(1);
};

function trans() {
    var input = $("#input");
    var value = input.val();

    // Retriving #customizing
    /*
      I retrieve the values of the input boxes, in order to replace them later
    */
    // needed or demonstration
    var IDa = $("#a").val();
    var IDb = $("#b").val();
    var IDc = $("#c").val();
    var IDd = $("#d").val();

    // Retriving #extra-customizing
    /*
      Using the same logic as the other ones
    */
    var ID_ax = $("#Ax").val(); // input
    var ID_ay = $("#Ay").val(); // output
    var ID_bx = $("#Bx").val(); // input
    var ID_by = $("#By").val(); // output
    var ID_cx = $("#Cx").val(); // input
    var ID_cy = $("#Cy").val(); // output
    /*
      If the user inputs something to replace, they MUST have something to to replace it with(may change later)
    */
    if (ID_ax != "" && ID_ax == "") {
        alert("You have not insterted a value in #1");
    }
    if (ID_bx != "" && ID_bx == "") {
        alert("You have not insterted a value in #2");
    }
    if (ID_cx != "" && ID_cx == "") {
        alert("You have not insterted a value in #3");
    }

    // Setting
    var mapObj = {
        // Setting #customizing
        /*
          I first select what the user would write, and the what it should be replaced with
        */
        a: IDa,
        b: IDb,
        c: IDc,
        d: IDd,
        A: IDa.cap(),
        B: IDb.cap(),
        C: IDc.cap(),
        D: IDd.cap()
    };
    
    // Extra customizing
    mapObj[ID_ax] = ID_ay;
    mapObj[ID_bx] = ID_by;
    mapObj[ID_cx] = ID_cy;
    
    // Translating
    /*
      Below is the code used to replace letters
    */
    var re = new RegExp(Object.keys(mapObj).join("|"), "g");
    console.log(re);
    value = value.replace(re, function (matched) {
        return mapObj[matched];
    });
    output.val(value);
}
body {
  background-color: #cccccc;
  color: #444444;
}

hr {
  width: 60%;
  background-color: #999999;
  border: none;
  padding: 0;
  margin: 0 auto 0 auto;
}

#customizing {
  font-family: "courier";
  width: calc(50em + 195px);
  width: -moz-calc(50em + 195px);
  margin: auto;
  font-size: .8em;
}

#extra-customizing {
  font-family: "courier";
  width: calc(55em + 282px);
  width: -moz-calc(55em + 282px);
  margin: auto;
  font-size: .8em;
  margin-top: .5em;
  padding-top: .5em;
  padding-left: .5em;
  padding-right: .5em;
  border-radius: 2px;
}

#customizing input, #extra-customizing input {
  font-family: "courier";
  width: 3em;
  margin-left: 5px;
  margin-right: 10px;
  font-family: "courier";
  text-align: center;
  font-size: .8em;
  padding-bottom: .3em;
  padding-top: .2em;
  background-color: #111111;
  color: #aaaaaa;
  border: none;
  border-radius: 2px;
  margin-bottom: 1em;
}

#extra-customizing input {
  margin-right: 15px;
}

#translator {
  width: 100%;
}


#extra-customize {
  width: 320px;
  margin: .2em auto 1em auto;
}

#extra-customize input {
  border: none;
  padding: 0;
  margin: 0;
  width: 1em;
  height: .9em;
}

#input {
  width: 40%;
  height: 40vh;
  float: left;
  padding: .43%;
  margin: 0;
  margin-left: 5%;
  border: none;
  background-color: #111111;
  color: #aaaaaa;
  border-radius: 2px;
  font-size: 1em;
  outline: none;
  resize: none;
  overflow: auto;
}

#inputB {
  font-family: "courier";
  width: 8.28%;
  padding: 0;
  margin: 0;
  padding-top: 3px;
  padding-bottom: 3px;
  border: none;
  background-color: #1f1f1f;
  color: #aaaaaa;
  border-radius: 2px;
  font-size: .8em;
  resize: none;
  cursor: pointer;
  outline: none;
}

#inputB:hover {
  background-color: #aaaaaa;
  color: #1f1f1f;
}

#output {
  width: 40%;
  height: 40vh;
  float: right;
  padding: .43%;
  margin: 0;
  margin-right: 5%;
  border: none;
  background-color: #111111;
  color: #aaaaaa;
  border-radius: 2px;
  font-size: 1em;
  outline: none;
  resize: none;
  overflow: auto;
}
</div><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="customizing">
  a<input type="text" id="a" value="a" maxlenght="3">
  b<input type="text" id="b" value="b" maxlenght="3">
  c<input type="text" id="c" value="c" maxlenght="3">
  d<input type="text" id="d" value="d" maxlenght="3">
</div>

<hr>

<div id="extra-customizing">
  1<input type="text" id="Ax" value="" maxlength="5">:<input type="text" id="Ay" value="" maxlength="7">
  2<input type="text" id="Bx" value="" maxlength="5">:<input type="text" id="By" value="" maxlength="7">
  3<input type="text" id="Cx" value="" maxlength="5">:<input type="text" id="Cy" value="" maxlength="7">
</div>

<div id="translator">
  <textarea id="input"></textarea>
  <input type="button" value="Translate" id="inputB" onclick="trans()">
  <textarea id="output" readonly></textarea>
</div>

最佳答案

如果您在“1”右侧的框中输入“chicken”和“nuggets”,您将得到以下正则表达式:

/a|b|c|d|A|B|C|D|chicken|/g

因此,它将尝试匹配包含 abcd、< em>A、BCD

由于在正则表达式列表中 c 位于 chicken 之前,并且 chickenc 开头,因此单词chicken永远不会匹配。

您应该做的是将单词放在正则表达式中的字母之前。你可以这样做:

var re = new RegExp(
  Object.keys(mapObj)
    .sort(function(a, b) {
      return b.length - a.length;
    })
    .join("|"),
  "g"
);

sort 函数会更改键的顺序,以便最长的单词排在前面。

正则表达式将变为:

/chicken|a|b|c|d|A|B|C|D|/g

片段

// My globals
var output = $("#output");
var extra_customizing = $("#extra-customizing");

String.prototype.cap = function () { // needed or demonstration
    return this.charAt(0).toUpperCase() + this.slice(1);
};

function trans() {
    var input = $("#input");
    var value = input.val();

    // Retriving #customizing
    /*
      I retrieve the values of the input boxes, in order to replace them later
    */
    // needed or demonstration
    var IDa = $("#a").val();
    var IDb = $("#b").val();
    var IDc = $("#c").val();
    var IDd = $("#d").val();

    // Retriving #extra-customizing
    /*
      Using the same logic as the other ones
    */
    var ID_ax = $("#Ax").val(); // input
    var ID_ay = $("#Ay").val(); // output
    var ID_bx = $("#Bx").val(); // input
    var ID_by = $("#By").val(); // output
    var ID_cx = $("#Cx").val(); // input
    var ID_cy = $("#Cy").val(); // output
    /*
      If the user inputs something to replace, they MUST have something to to replace it with(may change later)
    */
    if (ID_ax != "" && ID_ax == "") {
        alert("You have not insterted a value in #1");
    }
    if (ID_bx != "" && ID_bx == "") {
        alert("You have not insterted a value in #2");
    }
    if (ID_cx != "" && ID_cx == "") {
        alert("You have not insterted a value in #3");
    }

    // Setting
    var mapObj = {
        // Setting #customizing
        /*
          I first select what the user would write, and the what it should be replaced with
        */
        a: IDa,
        b: IDb,
        c: IDc,
        d: IDd,
        A: IDa.cap(),
        B: IDb.cap(),
        C: IDc.cap(),
        D: IDd.cap()
    };
    
    // Extra customizing
    mapObj[ID_ax] = ID_ay;
    mapObj[ID_bx] = ID_by;
    mapObj[ID_cx] = ID_cy;
    
    // Translating
    /*
      Below is the code used to replace letters
    */
    var re = new RegExp(
      Object.keys(mapObj)
        .sort(function(a, b) {
          return b.length - a.length;
        })
        .join("|"),
      "g"
    );
    console.log(re);
    value = value.replace(re, function (matched) {
        return mapObj[matched];
    });
    output.val(value);
}
body {
  background-color: #cccccc;
  color: #444444;
}

hr {
  width: 60%;
  background-color: #999999;
  border: none;
  padding: 0;
  margin: 0 auto 0 auto;
}

#customizing {
  font-family: "courier";
  width: calc(50em + 195px);
  width: -moz-calc(50em + 195px);
  margin: auto;
  font-size: .8em;
}

#extra-customizing {
  font-family: "courier";
  width: calc(55em + 282px);
  width: -moz-calc(55em + 282px);
  margin: auto;
  font-size: .8em;
  margin-top: .5em;
  padding-top: .5em;
  padding-left: .5em;
  padding-right: .5em;
  border-radius: 2px;
}

#customizing input, #extra-customizing input {
  font-family: "courier";
  width: 3em;
  margin-left: 5px;
  margin-right: 10px;
  font-family: "courier";
  text-align: center;
  font-size: .8em;
  padding-bottom: .3em;
  padding-top: .2em;
  background-color: #111111;
  color: #aaaaaa;
  border: none;
  border-radius: 2px;
  margin-bottom: 1em;
}

#extra-customizing input {
  margin-right: 15px;
}

#translator {
  width: 100%;
}


#extra-customize {
  width: 320px;
  margin: .2em auto 1em auto;
}

#extra-customize input {
  border: none;
  padding: 0;
  margin: 0;
  width: 1em;
  height: .9em;
}

#input {
  width: 40%;
  height: 40vh;
  float: left;
  padding: .43%;
  margin: 0;
  margin-left: 5%;
  border: none;
  background-color: #111111;
  color: #aaaaaa;
  border-radius: 2px;
  font-size: 1em;
  outline: none;
  resize: none;
  overflow: auto;
}

#inputB {
  font-family: "courier";
  width: 8.28%;
  padding: 0;
  margin: 0;
  padding-top: 3px;
  padding-bottom: 3px;
  border: none;
  background-color: #1f1f1f;
  color: #aaaaaa;
  border-radius: 2px;
  font-size: .8em;
  resize: none;
  cursor: pointer;
  outline: none;
}

#inputB:hover {
  background-color: #aaaaaa;
  color: #1f1f1f;
}

#output {
  width: 40%;
  height: 40vh;
  float: right;
  padding: .43%;
  margin: 0;
  margin-right: 5%;
  border: none;
  background-color: #111111;
  color: #aaaaaa;
  border-radius: 2px;
  font-size: 1em;
  outline: none;
  resize: none;
  overflow: auto;
}
</div><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="customizing">
  a<input type="text" id="a" value="a" maxlenght="3">
  b<input type="text" id="b" value="b" maxlenght="3">
  c<input type="text" id="c" value="c" maxlenght="3">
  d<input type="text" id="d" value="d" maxlenght="3">
</div>

<hr>

<div id="extra-customizing">
  1<input type="text" id="Ax" value="" maxlength="7">:<input type="text" id="Ay" value="" maxlength="7">
  2<input type="text" id="Bx" value="" maxlength="7">:<input type="text" id="By" value="" maxlength="7">
  3<input type="text" id="Cx" value="" maxlength="7">:<input type="text" id="Cy" value="" maxlength="7">
</div>

<div id="translator">
  <textarea id="input"></textarea>
  <input type="button" value="Translate" id="inputB" onclick="trans()">
  <textarea id="output" readonly></textarea>
</div>

关于javascript - 字母替换一个字符的麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30810155/

相关文章:

python - 模糊正则表达式(例如 {e<=2})在 Python 中的正确用法

javascript - 将按钮的值传给JS加载DIV内容

java - 从十进制字符串中删除前导零

javascript - 如何停止和重置我的倒数计时器?

javascript - 多级水平菜单 CSS

java - Android(Java)代码中的正则表达式疑问

javascript - 在数组中查找多个正则表达式

regex - 当格式不固定时,如何从 shell 变量的末尾提取时间戳?

javascript - 在 HTML5 Canvas 中滚动(不移动图像)图像

JavaScript : gauge image effect