Luca
Luca

Reputation: 20919

regex to take into consideration line break

The regex below replace the white space before the number with a comma:

var str="72 g tocirah snaeb 101 sgge 108 g darl 111 spuc loi 32  sinihccuz";
var result = str.replace(/ (\d+)/g, ", $1");

That work great, but when str is a multiline sentence like this:

var str="72 g tocirah snaeb
101 sgge
108 g darl
111 spuc loi
32  sinihccuz";
var result = str.replace(/ (\d+)/g, ", $1");

That doesn't work, so the regex isn't working normally. How to fix it so that it will take into consideration line break.

Upvotes: 0

Views: 186

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336098

You want to add a comma before whitespace that's followed by a number? Then you can use

result = str.replace(/(?=\s+\d)/g, ",");

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

Use \s to represent any space character (including newlines).

Upvotes: 4

Related Questions