skip to Main Content

I’m passing a string with jQuery, but it throws an Invalid or unexpected token error anytime there’s a CR+LF without a leading white space in front of it.

I’m trying to use the js function replaceAll() to fix these instances before passing the string, but I can’t seem to find the right syntax.

When I use replaceAll(new RegExp(/S+[rn]/g), " rn");, it replaces the S string, when I just want to replace the rn with a space + rn AFTER the S.

For example, I want:

This is the end
of the line

To become (underscore symbolizes a space character):

This is the end_
of the line

It’s important that if a line already ends with a space + CRLF, that we don’t add an additional space character.

UPDATE
Okay, I actually got a working regular expression:

replaceAll(new RegExp(/(?<=S)[rn]/g), " rn")

Unfortunately jQuery still throws a syntax error, HOWEVER, if I manually type the space character in front of the CRLF before submitting, I don’t get a syntax error. Very confused.

2

Answers


  1. Chosen as BEST ANSWER

    It turns out it was the r causing the syntax error, so now I'm just using:

    replaceAll(new RegExp(/(?<=S)[rn]/g), " n");


  2. I tried txt.replace(/ *$/mg," ") at first, but it would have changed "b n" into "b n" (by adding another blank to it). So, in the end I went for two replace operations:

    1. remove all blanks at the end of each line
    2. add a single blank at the end of each line
      const txt="anb nc  nd   ne f gnh";
      console.log("before:",JSON.stringify(txt));
      
      console.log("after:",JSON.stringify(txt.replace(/ *$/mg,"").replace(/$/mg," ")));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search