棘手的Javascript正则表达式替换

时间:2016-06-28 13:24:13

标签: javascript regex

我正在编写一个自定义降价分析器,它应该预处理用户输入,以便以三个标记开头的输入的每一行都应该修剪参考代码,并将所有空格替换为下划线。所以在这个小提琴中

var e = document.getElementById("thetext");
var feedback = document.getElementById("feedback");

var sorted = function(haystack) {
  var re = /$```\s*(\S+)(\s+)(\S+)\s*$/g;
  return haystack.replace(re, '```$1_$3');
};

e.addEventListener("blur", function(event) {
  feedback.innerHTML = sorted(e.value);
}, true);
textarea { width: 400px; height: 400px;}
<textarea id="thetext">
A custom block code marker with reference:

``` John 3:16
For God so loved the world 
``` 

another one with two spaces to be replaced:

```1 Cor 2:15-45 
Some other marked up text followed by white space 
```

</textarea>
<pre id="feedback">Tab out to see result</pre>

除了这两行之外,输出应该与输入完全相同:

```John_3:16

```1_Cor_2:15-45

2 个答案:

答案 0 :(得分:3)

使用回调函数可以轻松完成棘手的替换。

&#13;
&#13;
var thetext = document.getElementById("thetext");
var feedback = document.getElementById("feedback");

var sorted = function(haystack) {
  var re = /^```(.*)/gm;
  return haystack.replace(re, function ($0, $1) {
      return '```' + $1.trim().replace(/\s/g, '_');
  });
};

thetext.addEventListener("blur", function(event) {
  feedback.textContent = sorted(this.value);
});
&#13;
textarea { width: 400px; height: 400px;}
&#13;
<textarea id="thetext">
A custom block code marker with reference:

``` John 3:16
For God so loved the world 
``` 

another one with two spaces to be replaced:

```1 Cor 2:15-45 
Some other marked up text followed by white space 
```

</textarea>
<pre id="feedback">Tab out to see result</pre>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

你的正则表达式应该是多行的。 ^和$ anchors现在分别在每行的开头/结尾匹配,而不是整个字符串的开头/结尾。

/^```\s*(\S+)(\s+)(\S+)\s*$/gm;