ashley g
ashley g

Reputation: 885

Capitalise every first letter of a string in an array of strings

I am basically taking a URL like http://localhost:3000/north-america/america and then after the third slash putting each entry into an array.

I have an array of strings like this ["america", "north-america"].

I want to capitalise every first letter of each entry and each word in each entry and then join the strings back together to give me this result ["America", "North-America].

I also want to remove the dashes from any entry and replace them with a space giving me the final result of ["America", "North America].

So far I have managed to get this ["America", "North america"] but I am struggling to capitalise the second word.

const urls = "http://localhost:3000/north-america/america"

useEffect(() => {
    if (withAvailabilityChecker === true && urlS !== undefined) {
      const url = urlS;
      let parts: string[] = [];

      parts = url.split('/');
      parts.splice(0, 3);
      parts.reverse();
      parts.splice(0, 1);

      const newParts: string[] = [];

      parts.forEach(el => {
        const removeDashes = el.replaceAll('-', ' ');
        const capitaliseEntry = removeDashes.charAt(0).toUpperCase() + removeDashes.slice(1);
        newParts.push(capitaliseEntry);
      });

      if (newParts.length > 2) {
        newParts.length = 2;
      }
      const result = newParts.join(',' + ' ');

      setInputVal(result);
    }
  }, [urlS, locationName]);

Upvotes: 2

Views: 1483

Answers (4)

lejlun
lejlun

Reputation: 4419

Step by step is the best approach.

  • First split the URL using the / character as a divisor.
let parts: string[] = url.split("/")
  • Get rid of everything before the first three slashes.
parts = parts.slice(3)
  • Look through each item in the parts array for any - characters and remove them.
  • Split each item into separate words.
  • Capitalise the first letter of each word.
  • Join words back into an item.
parts = parts.map(item => {

    // Replacing dashes with spaces
    item = item.replace(/-/g, " ")

    
    item = item.split(" ") // Splitting each part into separate words
               .map(word => word[0].toUpperCase() + word.slice(1)) // Capitalising the first letter of each word
               .join(" ") // Joining back capitalised words

    return item
})
  • Finally reverse the array to put parts in the right order
parts = parts.reverse()

Full Verbose Solution

let url = "http://localhost:3000/north-america/america"

let parts = url.split("/")

parts = parts.slice(3)

parts = parts.map(item => {
  item = item.replace(/-/g, " ")
  
  item = item
    .split(" ")
    .map(word => word[0].toUpperCase() + word.slice(1))
    .join(" ")

  return item
})


parts = parts.reverse()


console.log(parts) // Outputs: ["America", "North America"]

Full Non-Verbose Solution

let url = "http://localhost:3000/north-america/america"

let parts = url
  .split("/")
  .slice(3)
  .map(item => {
    return item
      .replace(/-/g, " ")
      .split(" ")
      .map(word => word[0].toUpperCase() + word.slice(1))
      .join(" ")
  }).reverse()


console.log(parts) // Outputs: ["America", "North America"]

Upvotes: 1

pilchard
pilchard

Reputation: 12909

Using an URL object to isolate the pathname and split to return individual path strings. Then String#replace() with a regex and callback to simultaneously remove dashes and capitalize first letters.

const
  titleCase = (s) => s.replace(/\b([-\w])/g, m => m === '-' ? ' ' : m.toUpperCase()),

  url = "http://localhost:3000/north-america/america",

  data = new URL(url) // URL { href: 'http://localhost:3000/north-america/america', origin: 'http://localhost:3000', protocol: 'http:', username: '', password: '', host: 'localhost:3000', hostname: 'localhost', port: '3000', pathname: '/north-america/america', search: '', searchParams: URLSearchParams { }, hash: ''}
    .pathname         // "/north-america/america"
    .slice(1)         // "north-america/america"
    .split('/')       // ["north-america", "america"]
    .map(titleCase)   // ["North America", "America"]
    .reverse();       // ["America", "North America"]

console.log(data.join(', '));

Upvotes: 2

RishiMath
RishiMath

Reputation: 193

  • First things first, in your code
      parts = url.split('/');
      parts.splice(0, 3);
      parts.reverse();
      parts.splice(0, 1);

Why do you have the last line, aka parts.splice(0, 1)? Since as far I understood your question, you want all the entries from the 3rd slash, and this last line just removes the last element. So you gave the example of http://localhost:3000/north-america/america, by your code, it would simply return ["north-america"], not america since it is removed by the last line of your code.

  • On getting the array, you can map all the items to remove the Dashes first, then you could capitalize it. Like the following example.
const data = parts.map((element: string) => {
    const dashesRemoved = element.replace(/-/g, " ");
    const dashesRemovedWords = dashesRemoved.split(" ");
    const dashesRemovedCapitalized= dashesRemovedWords.map((word: string) => word[0].toUpperCase() + word.slice(1).toLowerCase());

    return dashesRemovedCapitalized.join(" ");
});

Now all these variables are for clarity on what's going on, and if you want, you can actually combine all those functions, like this

const data = parts.map((element: string) => element.replace(/-/g, " ").split(" ").map((word: string) => word[0].toUpperCase() + word.slice(1).toLowerCase()).join(" "));
  • Also I see you are declaring parts like this
      let parts: string[] = [];

      parts = url.split('/');

But you don't even have any intermediate code, or so it seems. Then wouldn't it be better to initialize your variable by

const parts: string[] = url.split("/");

Upvotes: 3

Mureinik
Mureinik

Reputation: 311163

I'd split the string by space, capitalize every word and join them back:

const capitaliseEntry = 
    removeDashes.split(' ').map(w => w[0].toUpperCase() + w.slice(1)).join(' ');

Upvotes: 4

Related Questions