Home > Blockchain >  Function to title case a string using javascript
Function to title case a string using javascript

Time:01-26

I'm currently working on a fix where there's an existing function that capitalizes each word of the given string. Each value that comes out of that function is later used to validate other logic.

So right now, that function is capitalizing texts in the wrong way. For example internet of things comes out as Internet Of Things and I need it as Internet of Things

This is the function with an adjustment I made, which is basically if the string contains "of" ignore it:

const cleanValue = value
        .replace(/-/g, ' ')
        .split(' ')
        .map((word, i) => {
            return word === 'of' && i != 0 ? word : word[0].toUpperCase()   word.substring(1);
        })
        .join(' ');

But my boss thinks it's a kind of hacky solution and is asking me to look for a better solution, I'm honestly having a hard time trying to fix this in a better way.

Any advice/ideas anyone could provide me on how to improve this?

Thank you!

CodePudding user response:

If you want to ignore some words then you can change your function like this.

const ignoreWords = ["of", "the", "and"];
const cleanValue = value
        .replace(/-/g, ' ')
        .split(' ')
        .map((word) => {
            return ignoreWords.includes(word.toLowerCase()) ? word : word[0].toUpperCase()   word.substring(1);
        })
        .join(' ');

CodePudding user response:

Not sure I love this idea--and it's not super efficient--but it's flexible enough to accommodate a bunch of arbitrary rules.

You could declare a set of transformers that each have 1) a predicate function that determines whether it handles a particular case, and 2) a function to do the transformation.

The last transformer in the set is the default. Its predicate always returns true, and it does capitalization.

Split the string into words and for each word find a transformer to handle it.

const lowerMiddleWords = ['a', 'at', 'of', 'and', 'the', 'for', 'with'];

const capitalize = (word) => word[0].toUpperCase()   word.substring(1);

const transformers = [
  {
    predicate: (word, index) => index && lowerMiddleWords.includes(word),
    transform: (word) => word,
  },
  {
    predicate: (word, index, phrase) => phrase.includes('hackers'),
    transform: (word) => capitalize(word.replaceAll('e', '3')),
  },
  {
    predicate: () => true,
    transform: capitalize,
  }
]

function transform(string) {
  return string.split(' ').map((word, index) => {
    const transformer = transformers.find((t) => t?.predicate(word, index, string));
    return transformer.transform(word);
  }).join(' ');
}

[
  "internet of things",
  "for the birds",
  "at peace with the world",
  "the good, the bad, and the ugly",
  "capitalize all of the things",
  "leet hackers like threes",
].forEach(str => console.log(transform(str)));

CodePudding user response:

So here's a javascript solution. Supose that you recive a string with name data

const ignoreWords = ["of", "the", "and"]; //used as references other codes from this post

function stringUpperCase(Data){

let ArrayOfStrings = Data.split(" ");
let ArrayUpperCased = [];
    
ArrayOfStrings.map((word) =>{

if(!ignoreWords.includes(word.toLowerCase())){

    ArrayUpperCased.push(word.charAt(0).toUpperCase()   word.slice(1)); //captalize the word
    return;
}
ArrayUpperCased.push(word.toLowerCase());
return ;
    
})

return ArrayUpperCased.join(" ");

}

stringUpperCase("Test Of Text")
// return 'Test of Text'

In this way you can customize the words that you want to ignore and the ones that you want to Uppercase;

  • Related