Home > Software engineering >  String manipulation in JS and React
String manipulation in JS and React

Time:06-04

I'm doing some string manipulation with API returned fields, and they have some unique characteristics, hence why I'm looking to try to adjust them.

For example:

one field comes from the JSON as: "contract_time": "full_time"

Provided this, I would like to try and manipulate it so that I get the output "Full Time".

I am calling it directly as the below:

          <BadgeComponentFirst>
            <Typography color="red" fontSize="0.6em">
              {job.contract_time}
            </Typography>

How would I pass such string manipulation to an object to first, remove the '_' and capitalise and the first of each word?

Thanks

CodePudding user response:

You want to split each word on '_' into an array, you can then map over the array and capitalize the first letter of each word. Then you want to join the words back together, separated by spaces. You can do:

let job = {
    contract_time: "full_time"
}

console.log(job.contract_time.split("_").map(word => word[0].toUpperCase()   word.substr(1)).join(' '));

console: Full Time

CodePudding user response:

The approach you need should differ if the API values for that field are a known in advance or not.

If the values are known in advance, use an object to map the known values to their user-facing equivalent:

const CONTRACT_TIMES = {
    full_time: "Full Time",
    part_time: "Part Time",
};

<Typography color="red" fontSize="0.6em">
    {CONTRACT_TIMES[job.contract_time] || "Unknown"}
</Typography>

If the API can return any value and you just want to display a cleaned up version, then write a function that does the manipulation you need:

function getFriendly(str) {
    return str.split("_").map(getFriendlyWord).join(" ");
}
function getFriendlyWord(word) {
    return word.slice(0, 1).toUpperCase()   word.slice(1);
}

<Typography color="red" fontSize="0.6em">
    {getFriendly(job.contract_time)}
</Typography>

CodePudding user response:

define a method transforms your data:

const capitalize = (str) => str[0].toUpperCase()   str.slice(1);

const verbose = (snake_cased) => {
    snake_cased.split('_').map(capitalize).join(' ');
};

And then you are free to use this transformer anywhere inside of JSX code without any limits. The only thing should keep in mind - this function will be fired every render. If this calculation is complicated - you may need some optimisation techniques.

const Component = () => (
    <BadgeComponentFirst>
        <Typography color="red" fontSize="0.6em">
            {verbose(job.contract_time)}
        </Typography>
    </BadgeComponentFirst>
);
  • Related