JavaScript: replace()

JavaScript: replace()

·

4 min read

I always forget that replace() exists. And when I do remember, I can't work out how to use it. Until recently...

What is it?

It pretty much does what it says on the tin: you can use it to replace a string with another string. Or part of a string with another string part. The MDN doc gives some good examples at the top of the page.

Sounds fun, but what is the point?

It turns out to be really useful. Who knew? Let's say that your friend has decided to encrypt their messages to you. Their encryption involves swapping the first and last letters in every word (unless the word has less than two letters, in which case they leave it alone). You want to write a script to decrypt it, because it's hard to read otherwise.

First, without using replace():

const message = 'shit si a eessagm mrof rouy drienf';
const messageArray = message.split(' '); //An array with each element being a word in the message
let decryptedMessage = [];
for(let i = 0; i < messageArray.length; i++) {
    if(messageArray[i].length < 2) {
        decryptedMessage.push(messageArray[i]);
    } else {
        const firstLetter = messageArray[i][0];
        const lastLetter = messageArray[i][messageArray[i].length-1];
        const restOfSentence = messageArray[i].substring(1, messageArray[i].length-1);
        decryptedMessage.push(lastLetter + restOfSentence + firstLetter);
    }
}
console.log(decryptedMessage.join(' ')); //this is a message from your friend

And now using replace():

const message = 'shit si a eessagm mrof rouy drienf';
const messageArray = message.split(' '); //An array with each element being a word in the message
let decryptedMessage = [];
for(let i = 0; i < messageArray.length; i++) {
    decryptedMessage.push(messageArray[i].replace(/(^\w)(\w*)(\w$)/, '$3$2$1'));
}
console.log(decryptedMessage.join(' ')); //this is a message from your friend

You might look at that and say "You said you were going to explain replace(), you didn't say anything about regex". And you might also say "It's shorter, but not much shorter". Both valid objections. I'll deal with them one at a time.

Regex

Explaining regex if you've never come across it is beyond the scope of this post But even if you know regex, it can often just look like a jumble of letters and punctuation. I recommend this online regex tester : it reminds you what everything means and allows you to see which bits your regex is matching.

The regex I used breaks down into three parts:

  1. (^\w) means match the first letter
  2. (\w*) means match zero or more letters
  3. (\w$) means match the last letter

This is clever stuff because for any length of word it will pick out the first and last letters, plus any number in between. And if there's only one letter, it will ignore it.

What are all those dollars about?

replace() works like the find & replace in your text editor. The first part, before the comma, is the part you're looking for. The second part, after the comma, is the part you want to replace it with. The dollar signs($) are used to stand in for the bits you've found.

We have $3$2$1 - three parts to match the three parts we found. The numbers stand in for the parts of the regex, so $1 is point 1 above, $2 is point 2 and $3 is point 3. So we can go through the replace in three stages:

  1. Find the first letter and replace it with the last
  2. Find any letters that aren't the first and last and replace them with themselves
  3. Find the last letter and replace it with the first

OK, but do you have to do it all at once?

Yes. Well, arguably you could just replace the first and last letters and not worry about the ones in between, but in the interests of keeping the two examples as similar as possible, I wanted to still push everything to a new array.

But what you can't do is to replace the last letter with the first and then the first letter with the last. Here's what happens if you replace the last letter with the first:

this -> thit

The s has gone, so now you can't move it to the front of the word.

OK, so it's clever. But do we need to be that clever?

No, in this simple example it doesn't matter too much. But what if your friend then decided his encryption method wasn't good enough. Now he's going to swap the first and last letters. then swap the second and fourth. Then third and fifth.

Using the loops, you'd have a lot more rows. More if statements to cope with words below two letters, four letters and five letters. And the four lines within the else would become twelve. Whereas with the replace, that one line would become three.

So now clever, replace() solution is now simpler: shorter, easier to read and less likely to be wrong somewhere.

The dollars are your friends.

sharon-mccutcheon-8lnbXtxFGZw-unsplash.jpg Photo by Sharon McCutcheon on Unsplash

Cover photo by Miguel A. Amutio on Unsplash