For the first time ever, I have the need to manipulate a string quite heavily in JS. After playing around I've noticed how out of hand it can get. I'm no JS pro and I'm guessing there's a cleaner way to achieve my desired output?
Question:
Is editing the sample string x, like I have done necessary or is there a better solution?
My goal is to go from this:
_postcode_pricing_manual_weekend_eveningto this:Manual Weekend Evening:
const x = '_postcode_pricing_manual_weekend_evening'; // Original String
console.log("Original:", x);
var str = x.replace('_postcode_pricing_',''); // Strip prefix
console.log('1:',str);
var finalStr = str.replace(/_/g, ' '); // strip Underscores
console.log('2:',finalStr);
// Add ':'
finalStr = finalStr = ':';
// Split into words array
const words = finalStr.split(" ");
// Loop array capitalise first letter of each word '[0]'
for (let i = 0; i < words.length; i ) {
words[i] = words[i][0].toUpperCase() words[i].substr(1);
}
// Put array back together.
console.log("Final output:",words.join(" "));
CodePudding user response:
If by "merge" you mean chain multiple replaces together, yes.
str = x.replace('_postcode_pricing_', '').replace(/_/g, ' ') ':'
...is perfectly acceptable.
CodePudding user response:
Yes, you can chain methods, so long as the previous method returns a type that implements the next method in a chain.
As for your process, you have some redundancy. You replace underscores with spaces, but then discard those spaces with your split() call. You could simply split on undercscores.
const x = '_postcode_pricing_manual_weekend_evening'; // Original String
console.log("Original:", x);
var words = x
.replace('_postcode_pricing_','') // remove prefix
.split("_") // split into words
.map(word => word[0].toUpperCase() word.slice(1)) // capitalize
.join(" "); // rejoin
console.log(`${words}:`); // final literal adding ':'
