.replace working inconsistently

I’m trying to solve test 8 for the Markdown Previewer app which is to insert a <br> element anytime there is a carriage return.

For some reason, when I try to replace text inside the marked renderer function it doesn’t work, even though it does work outside the function.

Here is an example on CodePen

When I call replaceText() on a string normally it replaces the \r with a <br> as intended.

However, when called inside the renderer.text method it returns a different string than before.

Any ideas at what’s going on?

Thanks in advance.

Put the following inside your myRender.text function, so you can see what is being passed into the function. I think you will be surprised.

myRenderer.text = function(text) {
  console.log('inside myRenderer.text - text before replaceText called')
  console.log(text);
  console.log(replaceText(text));
  console.log('inside myRenderer.text - text after replaceText called')
  //return replaceText(text);
}

I don’t see anything unusual. Looks like its passing the original string to me…
Here is the output I see (I’ve added a print at the top as well):

“text before any action:”
“this is a line
new line”
“Calling replaceText() normally:”
“this is a line
new line”
“Calling replaceText() inside marked():”
“inside myRenderer.text - text before replaceText called”
“this is a line
new line”
“this is a line
new line”
“inside myRenderer.text - text after replaceText called”

Since you are passing the string “this is a line \r new line” to marked, I find it interesting that the console.log(text) string does not also show “this is a line \r new line”, but the marked function must do some pre-processing as it is passed into the function? I ask, because I have never used marked.js before and have not read about it at all. My observation may seem naive since, based on me not using marked.js before.

the console.log(text) string does not also show “this is a line \r new line”,

Yeah, the thing is using console.log() outside of marked results in the same output. I’m also not super familiar with Marked.js but as far as I can tell my renderer.link method should override the default completely. Here is the relevant docpage.

I went and looked at the marked.js source and it looks like it does in fact preprocess the strings it receives and replaces all \r's with \n's. Looks like I’ll have to deal with \r myself.

1 Like

That is kind what I was implying in my response, but I had not read the documentation to confirm. Good to know for future reference.

Yup, thanks for pushing me in the right direction