Nerd For Tech
Published in

Nerd For Tech

Basics of Javascript · String · replace() (method)

This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.

Hello devs! The method of the day can be simple to use, but at the same time, it can be a real pain in the back. We will be replacing stuff today. Meet method replace(). Let’s dive right in.

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern is the first parameter and it can be either Regular Expression or simple string value. The replacement is a second parameter and it can be either a simple string value or it can be a function to be called for each match. If the pattern is a string value or the Regular Expression does not contain a global flag, only the first occurrence will be replaced.

Let’s cover all the combinations in the first example.

const str = "The blue sweater itches. I'll wear a red t-shirt and a blue jeans.";let regExp = /blue/g;
let regExp2 = /blue|red/gi;
// PATTERN: string
// REPLACEMENT: string
"S -> S : " + str.replace("blue", "green")
// OUTPUT:
// S -> S : The green sweater itches. I'll wear a red t-shirt and // a blue jeans.
// PATTERN: RexExp
// REPLACEMENT: string
"RE -> S : " + str.replace(regExp, "green")
// OUTPUT:
// RE -> S : The green sweater itches. I'll wear a red t-shirt and // a green jeans.
// PATTERN: string
// REPLACEMENT: function
console.log
(
"S -> fn : " +
str.replace
(
"sweater",
(x) => {
return x.toUpperCase()
}
)
);
// OUTPUT:
// S -> fn : The blue SWEATER itches. I'll wear a red t-shirt and a // blue jeans.
// PATTERN: RexExp
// REPLACEMENT: function
console.log
(
"RE -> fn : " +
str.replace(
regExp2,
function (x)
{
return x.toUpperCase()
}
)
);
// OUTPUT:
// RE -> fn : The BLUE sweater itches. I'll wear a RED t-shirt and a // BLUE jeans.

There are four available combinations of “pattern” and “replacement” types of values.

First one is the simplest one. We are looking for a string “blue” and replacing it with string “green”. The first found occurrence of string is replaced. Not all of them.

The second case is using a regular expression to find a match to replace with the simple string value of “green”. Since we are using the global flag within our regular expression, we will be replacing all of the matches, not just the first one.

The third case is a simple string “sweater” being replaced by a function. Our function transforms any match to all uppercase characters. Since we are using a simple string as a pattern, only the first match is replaced.

The last — fourth case — is a regular expression match being replaced by function. We again use a global flag, so we are finding all the matches, not just the first one, and we are replacing them to an uppercase version of the matched word.

I spanned the last two cases into multiple lines, so it is easier to read, but you can put everything in one line if you like. It really doesn’t make any difference.

You can do a lot of cool tricks with the replace method. I picked some of them, to show you all the possibilities.

The second example shows you how to easily switch the order of the first and last name. If you have an array or list of names, this can come really handy.

let re = /(\w+)\s(\w+)/;
let fullName = 'John Smith';
let newstr = fullName.replace(re, '$2, $1');
newstr // Smith, John

Our regular expression specifies two groups of characters separated by an empty space. You can access this group using the dollar sign symbol and group’s order of creation — starting with one for the first one. We have two groups $1 and $2. First represents the first name and the second one the last name. All we need to do is switch their order in the output.

The next trick can come in handy if you need to parse between CSS styles and the JS style parameters. Javascript allows you to style elements using the style method, but it accepts CSS styles in a camelcase format instead of hyphen format. So if you want to change the left padding value, you would type “paddingLeft” instead of “padding-left”. And luckily for you, there is a simple way to transform camelcase format to hyphen format with the help of replace() method.

function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? '-' : '') + match.toLowerCase();
}
function camelCaseToHyphenFormat(propertyName) {
return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
camelCaseToHyphenFormat("marginBottom") // margin-bottom

The whole principle of the transformation is that we are looking for capital letters within the given string. If we find one, we replace it not only with its lowercase version, but we also prefix it with hyphen. And that’s it.

The last trick makes it possible to convert physics units of temperature from Fahrenheit degrees to Celsius. I slightly tweaked the original version of the function to accept values even if there is space between number and letter F denoting Fahrenheit degrees. And also it puts the space between the resulting number and Celsius degrees.

function f2c(x) {
function convert(str, p1, offset, s) {
return ((p1 - 32) * 5/9).toFixed(2) + ' C';
}
let s = String(x);
let test = /(-?\d+(?:\.\d*)?)( )*F\b/g;
return s.replace(test, convert);
}
f2c("212 F") // 100.00 C
f2c("0F") // -17.78 C

You can call the method simply by providing any numeric value followed by the letter “F”. The result is the same temperature in Celsius degrees.

Okay, this was real fun, but all good things must come to an end. This is it for us today. As always, thanks for your attention and I will see you next time with yet another method.

--

--

--

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Recommended from Medium

Setting Up Navigation for React Native App

避 (Japanese Kanji) — evade, avoid, avert, ward off, shirk, shun

Greatly reduce your React app bundle size with Bit components

Duckweed, the true UI microframework

Creating Firefox browser extensions-23

4 Dangerous Problems in JavaScript Easily Solved by the Builder Design Pattern

React 101.0

Build A Multiple Choice Trivia Game — React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jakub Korch

Jakub Korch

Web enthusiast, programmer, husband and a father. Wannabe entrepreneur. You name it.

More from Medium

Conclusion : Angular or React?

Map, Filter and Reduce in Javascript

Angular vs React

State management in Angular using NgRx