Insert Carriage return every 2 words using regex and javascript -


i'd make regex inserts carriage return every 2 words... string format in array(does make difference?) problem : heard regex 2 weeks ago , far makes me feel litterally stepping on brain. moment came (bear 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 me?

also when i'm done this, need make 1 replacing end of sentence '...' when sentence exceeds number of characters. if have insights on since i'll 1 also... searched site, found replacing end of sentences carriage returns. , i'm guessing pb lies in defining of word. bunch

spoilt choice, are. thought add 1 more option, , answer second question @ 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 - last word ('adipisicing') not matched, not replaced. it's there @ end (and without trailing \n).

explanation:

regexp:

(     start capture group comprising: \w+   1 or more "word" characters \w+   1 or more "not word" characters \w+   1 or more "word" characters )     end capture group \w    followed non-word /ig   case insensitive, global (repeat possible) 

and replace with:

$1    "the thing in first capture group (everything matched in parentheses) \n    followed newline 

second question:

by way - since asking "other" problem - how terminate sentence in ... after number of words, 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 used counting) \w+  1 or more "word" characters \w+  1 or more "non word" characters ){5} match 5 of these )    end of capture group .*$  followed number of characters end of string 

and replace with

$1   contents of capture group (the first 5 words) ...  followed 3 dots 

there - 2 answers 1 question!

if want both, "abbreviate long sentence" first, cut shorter segments. it's bit harder count words across multiple lines regex.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -