Reputation: 3
With use of JavaScript/jQuery and RegEx I would like to remove all instances of the word 'Integer' from paragraph below and first word after the deleted word should be capitalized.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam elit massa, maximus in turpis vel, viverra iaculis nisl. Nullam pulvinar mi eu metus posuere, a porta ligula feugiat. Integer quis nunc neque. Etiam sollicitudin diam in dolor sagittis pellentesque. Nunc placerat sollicitudin purus. Proin mattis, quam sit amet pellentesque blandit, urna erat mollis sapien, et vestibulum nunc mi sed orci. Integer ligula tellus, maximus id orci quis, euismod consequat nulla.
My attempt so far for removing desired word:
var modified = $(".paragraph").html();
modified = modified.replace(/Integer\s/g, '');
But after that I don't know how to dynamically access the next word (from above example text word: 'quis' and 'ligula') and set it to be capitalized. One note: the word that needs to be deleted is always the same, but word after is always different.
Upvotes: 0
Views: 468
Reputation: 769
To be sure of getting a capitalized word every time after removing Integer, use the following:
modified = modified.replace(/Integer\s+(\w)/g, function(fullMatch, capturedGroup) {
return capturedGroup.toUpperCase();
});
Note: This would even match Integer followed by Capitalised words. If you want to select only instances of Integer followed by lowercase words, then use [a-z]
instead of \w
in the above regex.
Upvotes: 1
Reputation: 791
there is maybe a way with replace directly, but i would do it like this maybe:
let textResult;
do {
textResult = /Integer\s(.)/gs.exec(modified);
if (!textResult || !textResult[1]) {
textResult = null;
continue;
}
modified = modified.replace('Integer ' + textResult[1], textResult[1].toUpperCase());
} while (!!textResult);
Upvotes: 0
Reputation: 1215
Not a regex but this one liner can fulfil your purpose.
let str = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam elit
massa, maximus in turpis vel, viverra iaculis nisl. Nullam pulvinar mi eu metus
posuere, a porta ligula feugiat. Integer quis nunc neque. Etiam sollicitudin diam
in dolor sagittis pellentesque. Nunc placerat sollicitudin purus. Proin mattis,
quam sit amet pellentesque blandit, urna erat mollis sapien, et vestibulum nunc
mised orci. Integer ligula tellus, maximus id orci quis, euismod consequat nulla.`;
str.split(/Integer\ /g).map(part=>{return part.charAt(0).toUpperCase() + part.substr(1)}).join("")
Upvotes: 0