skip to Main Content

for example i am using :

string.replace(/s+/g, " ").trim();  // here string being my string name

it replaces all extra spaces with a single space along with line breaks as well.
But i want the line breaks to stay as they are while the extra spaces in a line to be replaced with a single space

2

Answers


  1. You could use the following negative character class trick here:

    string.replace(/[^Sn]/g, " ").trim();
    

    The pattern [^Sn] matches:

    • Not S, which is equivalent to s (what you currently have)
    • But also not n, which spares newlines from being replaced
    Login or Signup to reply.
  2. You could use the following negative character class trick here:

    string.replace(/[^Sn]/g, " ").trim();
    The pattern [^Sn] matches:

    Not S, which is equivalent to s (what you currently have)
    But also not n, which spares newlines from being replaced

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search