2

I'm coding a custom markdown parser that should preprocess user input so that each line of the input that starts with three ticks should have the reference code trimmed and all it's spaces replaced with underscores. So in this fiddle

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>

the output should be exactly like the input except for these two lines:

```John_3:16

and

```1_Cor_2:15-45

2 Answers 2

3

Tricky replacements are done easiest with a callback function.

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);
});
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>

Sign up to request clarification or add additional context in comments.

3 Comments

$1.replace(/^\s+|\s+$/g, '').replace(/\s/g, '_') ==> $1.trim().replace(/\s+/g, '_');
@Tushar Nice. Apparently I'm too old-school for that.
Wow! didn't know you can use a callback. Thanks for the great introduction.
2

Your regex should be multiline . The ^ and $ anchors now match at the beginning/end of each line respectively, instead of beginning/end of the entire string.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.