So essentially what I'm trying to do is loop through every word in a html document and replace the first letter of each word with 'A', the second - second last letter with 'b' and the last letter with 'c', completely replacing the word. I'm not sure if regular expressions are the way to go about doing this (should I instead be using for loops and checking each character?) however I'll ask anyway.
Currently I'm doing:
document.body.innerHTML = document.body.innerHTML.replace(/\\b(\\w)/g, 'A');
to get the first letter of each word
document.body.innerHTML = document.body.innerHTML.replace(/\\w\\b/g, 'c');
to get the last letter of each word
So if I had the string: Lorem ipsum dolor sit amet
I can currently make it Aorec Apsuc Aoloc Aic Amec
but I'd like to do Abbbc Abbbc Abbbc Abc Abbc
in javascript.
Any help is much appreciated - regular expressions really confuse me.
You almost got it.
str = "Lorem ipsum dolor sit amet" str = str .replace(/\\w/g, 'b') .replace(/\\b\\w/g, 'A') .replace(/\\w\\b/g, 'c') document.write(str);
Fancier replacement rules can be handled with a callback function, eg
str = "Lorem ipsum dolor sit amet" str = str.replace(/\\w+/g, function(word) { if (word === "dolor") return word; return 'A' + 'b'.repeat(word.length - 2) + 'c'; }); document.write(str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.