How to break paragraph into sentences in jquery

I want to break a paragraph into sentences in jquery. Let's say I have a paragraph

This is a wordpress plugin. its older version was 2.3.4 and new version is 2.4. But the version 2.4 had a lot of bungs. Can we solve it?

I want to break it into

This is a wordpress plugin.
its older version was 2.3.4 and new version is 2.4.
But the version 2.4 had a lot of bungs.
Can we solve it?

is there any solution for this. I tried to use this function, but it is also a separate sentence when the number arrived.

var result = str.match( /[^\.!\?]+[\.!\?]+/g );

thank

+4
source share
1 answer

You can use something like /((\.|\?|\!)\s)|(\?|\!)|(\.$)/gto get elements. Here is a pseudo-breakdown of each capture group:

  • ((\.|\?|\!)\s): any ., ?or !followed by spaces.
  • (\?|\!): any standalone ?or !.
  • (\.$): any .followed by end-of-line. (this may be unnecessary depending on the line)

, :

console.clear();
var str = 'This is a wordpress plugin. its older version was 2.3.4 and new version is 2.4. But the version 2.4 had a lot of bungs. Can we solve it?';
console.log('"' + str + '"');
console.log('Becomes:');
console.log('"' + str.replace(/((\.|\?|\!)\s)|(\?|\!)|(\.$)/g, ".\n") + '"');
Hide result

" " :

console.clear();
var str = 'This is a wordpress plugin. its older version was 2.3.4 and new version is 2.4. But the version 2.4 had a lot of bungs. Can we solve it?';
str = str
  //"all"
  //.replace(/((\.|\?|\!)\s)|(\?|\!)|(\.$)/g,".\n")
  //"."
  .replace(/((\.)\s)|(\.$)/g, ".\n")
  //"?"
  .replace(/((\?)\s)|(\?)/g, "?\n")
  //"!"
  .replace(/((\!)\s)|(\!)/g, "!\n")
console.log(str)
Hide result
+5

Source: https://habr.com/ru/post/1648786/


All Articles