0

I would like the replace all the spaces in my project. And my project has many \n. But when I replace the space, and the \n be replaced at the same time.

For example

var s = '1\n'; 
var re = s.replace(/\s/g,"**");
console.log(re); //1**

I don't expect this result

mikezhou
  • 25
  • 3
  • `\s` matches all white-space characters which include Newlines too. Instead of a `\s`, you can use a space in `var re = s.replace(/ /g,"**");` – Gurmanjot Singh Jul 18 '19 at 02:52

1 Answers1

0

\s normally matches: space, tab, newline, carriage return, and vertical tab.

I think what you want is / |\t/g (space or tab) rather than /\s/g.

If you really want to replace only the spaces, use / /g.

Rocky Sims
  • 2,316
  • 1
  • 10
  • 13
  • Great, I check it from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions \s matches a white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. Thanks for your great help. – mikezhou Jul 18 '19 at 03:08