2

How can i use regexp with .slice() in order to save my punctuation at the end of each line? Lets say i have a description which looks like this:

<div class="desc">We have text. About specific product? Or feature!</div>

I want it to look like this:

<div class="desc">
<ul>
<dd>We have text.</dd>
<dd>About specific product?</dd>
<dd>Or feature!</dd>
</ul>

for me jQuery is ok in this specific case, so i have build this:

jQuery(function() {
    var description = jQuery('div.desc');
    var sentences = description.text().split(/\.|\?|\!\s+/g),
    $wrapper = description.empty();

    jQuery.each(sentences, function(_, sentence) {
          jQuery('<dd>', {text: sentence}).appendTo($wrapper);
        });
        jQuery('.desc > dd').wrapAll("<ul></ul>");
        jQuery('.desc > ul > dd:last-child').remove();
});

and it works perfecly fine EXEPT -> slicing by "." "!" "?" - removes these signs. I need to keep them..

i also thought about something like:

var myStr = 'We have text. About specific product? Or feature!';
var strArray = myString.split('.');

after that i can use this (just for example):

alert('!' + strArray[1]);

BUT the thing is that description is always different. So if on one page "?" sign will be at the end of first sentence -> page number two will have it after sentence number 6.

2 Answers2

3

You could take match instead of split.

var string = 'We have text. About specific product? Or feature!';

console.log(string.match(/.*?[.!?](\s+|$)/g));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • He still has to split the string up though. How will this answer address that? – Scott Marcus Apr 17 '19 at 16:54
  • @ScottMarcus, i don't understand. – Nina Scholz Apr 17 '19 at 16:57
  • 1
    My mistake. I thought that `.match` simply returns a Boolean, not an Array. Got it confused with `.test()`. – Scott Marcus Apr 17 '19 at 17:00
  • @NinaScholz Thank you! Works great. The end result looks like this: (maybe somebody will need this) jQuery(function() { var description = jQuery('div.desc'); var sentences = description.text().match(/.*?[.!?](\s+|$)/g), $wrapper = description.empty(); jQuery.each(sentences, function(_, sentence) { jQuery('
    ', {text: sentence}).appendTo($wrapper); }); jQuery('.desc > dd').wrapAll("
      "); });
      –  Apr 17 '19 at 17:00
    -1

    If you use a capturing group in your regex, it will preserve the matched charactes.

    let myStr = 'We have text. About specific product? Or feature!';
    let strArray = myStr.split(/([.?!])/);
    
    console.log(strArray );
    junvar
    • 11,151
    • 2
    • 30
    • 46