0

I have a string that I need to replace in a document. The tricky part is that the text must match but the spaces can be new lines. So I have var myString = 'a b c' and need to match instances like 'a b c' and 'a\nb c'.

I think /a\sb\sc/ is the expression I want, but am not sure how to turn the original string into that expression.

I've tried RegExp(myString.replace(/ /g, '\s')) which gives me /asbsc/.

Please show me how I can turn the given string into the correct regular expression.

rurp
  • 1,376
  • 2
  • 14
  • 22
  • 2
    Use `'\\s'`.... – Wiktor Stribiżew Jul 19 '17 at 21:16
  • 1
    since the backslash is the escape character in a string (to escape the quote), to figure it you need to escape it with an other backslash. – Casimir et Hippolyte Jul 19 '17 at 21:16
  • I would think just hand typing `\\s` where space is should be sufficient. why the need to run a regex on that regex to do that? –  Jul 19 '17 at 21:19
  • @WiktorStribiżew Thanks, that works. Probably a dumb question but why does ```myString.replace(/ /g, '\\s')``` return ```'a\\sb\\sc'```? I had actually tried that but thought the double slashes in the output looked wrong. – rurp Jul 19 '17 at 21:25
  • They are not doubled, it is only how the *literal strings* are "coded" as *string literals*. – Wiktor Stribiżew Jul 19 '17 at 21:27

0 Answers0