YaBCK
YaBCK

Reputation: 3029

Replace numbers dynamically which exist next to a certain word or certain characters? (JavaScript)

I want to be able to replace numbers before a certain characters dynamically?

In the example below I'd want to target the numbers next to kW - The reason why I'm wanting to replace is that the values aren't generated by myself, I'm grabbing a list of products from a database which I don't control as I would of done exactly @Winter has mentioned.

Original:

Torch 90kW
Toy Car 340kW
Battery 120kW
Electric Toothbrush 5kW

Replace to:

Torch 10kW
Toy Car 90kW
Battery 40kW
Electric Toothbrush 15kW

What currently have, the only reason why I don't want to use this:

/*  Only reason why i'm not wanting to use this is because if there was digit before hand then they'll  get replace aswell. 

As you can see below the 200 and 30 would get replaced. */

let stringToReplace = '200 Toy 30Kw';
stringToReplace = stringToReplace.replace(/\d+/g, "20");

document.write(stringToReplace);

Upvotes: 0

Views: 121

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272006

A simple String.replace and some regex:

"Electric Toothbrush 15kW".replace(/\d+(?=kW)/, "999");
// Electric Toothbrush 999kW

This method can also accept a callback function:

"Electric Toothbrush 15kW".replace(/\d+(?=kW)/, match => Number(match) * 10);
// Electric Toothbrush 150kW

Upvotes: 1

a.mola
a.mola

Reputation: 4011

You can use a regex to select the digits followed by the kW. And replace it to your desired value

const testCases = [`Torch 90kW`, `Toy Car 340kW`, `Battery 120kW`, `Electric Toothbrush 5kW`];
const testNums = [10, 90, 40, 15];

const regex = /\d+kW/;

console.log(testCases.map((a, i) => a.replace(regex, `${testNums[i]}kw`)))

Upvotes: 1

Winter
Winter

Reputation: 326

You can use template literals for all these.

Example:

let torchNumber = 40; 
// 40 would be your dynamic number
let torchString = `Torch ${torchNumber}kW`
//Your dynamic code should be inside ${}
console.log(torchString)

Upvotes: -1

Related Questions