简体   繁体   中英

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 break 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: /.(?=[AZ])/g

The javascript is: description.replace(/.(?=[AZ])/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

For more complex sentence structures, including quotes, parenthesis, etc. this is the solution I came up with ( gist ):

  1. Regular expression:

     ([^\\dA-Z][\\.!?][\\)\\]'"”']* +) 
  2. Replace string:

     $1\\n 

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(/.(?=[AZ])/g, '<br /><br />');

becomes

description.replace(/\\.(?=[AZ])/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 />');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM