I'd like to make a regex that inserts a carriage return every 2 words... Also the string to format is in an array(does that make any difference?) the problem is : I heard about regex 2 weeks ago and so far it makes me feel like someone is litterally stepping on my brain. So for the moment I came up with that (bear with me...)
ticketName[i] = 'Lorem ipsum dolor sit amet consectetur adipisicing';
ticketName[i] = ticketName[i].replace(/(?:[a-zA-Z])* {2}/ig, ',');
Surprisingly...it doesn't work !
Can anyone help me?
Also when I'm done with this, I will need to make another one replacing the end of the sentence by '...' when the sentence exceeds a certain number of characters. if you have any insights on that since I'll probably be back for that one also... Searched the site, only found replacing end of sentences with carriage returns. and I'm guessing my pb lies in the defining of the word. Thanks a bunch
Spoilt for choice, you are. I just thought I would add one more option, and answer your second question at the same time:
var mytest = "lorem ipsum dolor sit amet consectetur adipisicing";
var newtext = mytest.replace(/(\w+\W+\w+)\W+/ig,"$1\n");
alert(newtext);
result:
lorem ipsum
dolor sit
amet consectetur
adipisicing
Note - the last word ('adipisicing') was not matched, so not replaced. It's just there at the end (and without a trailing \n).
Explanation:
Regexp:
( start a capture group comprising:
\w+ one or more "word" characters
\W+ one or more "not a word" characters
\w+ one or more "word" characters
) end capture group
\W followed by non-word
/ig case insensitive, global (repeat as often as possible)
and replace with:
$1 "The thing in the first capture group (everything matched in parentheses)
\n followed by a newline
second question:
By the way - since you were asking about the "other" problem - how to terminate a sentence in ... after a certain number of words, you could do the following:
var abbrev = mytest.replace(/((\w+\W+){5}).*$/,"$1...");
alert(abbrev);
result:
lorem ipsum dolor sit amet ...
Explanation:
( start capture group
( start second group (to be used for counting)
\w+ one or more "word" characters
\W+ one or more "non word" characters
){5} match exactly five of these
) end of capture group
.*$ followed by any number of characters up to the end of the string
and replace with
$1 the contents of the capture group (the first five words)
... followed by three dots
There - two answers for one question!
If you want to do both, then do the "abbreviate a long sentence" first, then cut it into shorter segments. It's a bit harder to count words across multiple lines with regex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With