javascript regex to add line break after period
Im trying to use a regex in javascript to add a line break after every sentence to json data that is being formatted as an html variable.
Locating it based just on the period wasnt working -- there seemed to be extra characters in the json data or something else that was causing line breaks every 3 or 4 words.
So Im trying to search for a period with the look-ahead for a capital letter. But this is adding the line br开发者_JAVA百科eak before every capital letter, not just ones that follow a period.
Im pretty new to regular expressions so any help would be very very helpful!
Right now the search parameter for the period followed by a capital letter is: /.(?=[A-Z])/g
The javascript is: description.replace(/.(?=[A-Z])/g, '<br /><br />');
Couple of issues.
First .
in RegExp means, "any character".
Second, I don't think you need the ?=
. I think you're probably looking for something like this:
/\.(\s+)[A-Z]/g
A period .
is a wildcard that matches any single character. To match an actual period you must escape it in the regex \.
so your line
description.replace(/.(?=[A-Z])/g, '<br /><br />');
becomes
description.replace(/\.(?=[A-Z])/g, '<br /><br />');
I haven't done any testing on this to check the rest of the regex.
You need to escape your .
like this `.' so it doesn't match any character.
description.replace(/\.(?=[A-Z])/g, '<br /><br />');
For more complex sentence structures, including quotes, parenthesis, etc. this is the solution I came up with (gist):
Regular expression:
([^\dA-Z][\.!?][\)\]'"”’]* +)
Replace string:
$1\n
精彩评论