I am trying to format a string in JavaScript as stated in the title e.g. "item:sample_text"
to "Sample text"
. Another example would be "item:longer_sample_text"
to "Longer sample text"
.
I know how to do it, but I wonder if it could be done in a more efficient or a cleaner way.
const stringTokens = originalString?.split(':');
if (!stringTokens) return '';
const stringToChange = stringTokens[stringTokens.length - 1];
const finalString = stringToChange[0].toUpperCase() stringToChange.slice(1).replace('_', ' ');
This looks a bit ugly and I think it could be done better. Any ideas?
CodePudding user response:
A little cleaner
const stringToChange = stringTokens.pop()
Instead of
const stringToChange = stringTokens[stringTokens.length - 1];
CodePudding user response:
You can simply achieve this by using RegEx
with the JavaScript methods String.match()
and String.replaceAll()
.
- The regex pattern is
/:(.*)/
matches the characters after:
in a string. - The regex pattern is
/^./
matches the first character of a string.
Live Demo :
// Input string
const str = "item:longer_sample_text";
// Regex to get the matched sub string.
const stringToChange = str.match(/:(.*)/)[1];
// Regex to capitalize first character of a string.
const capitalized = stringToChange.replace(/^./, stringToChange[0].toUpperCase());
// final String
const finalString = capitalized.replaceAll('_', ' ');
// print the output
console.log(finalString);