MKBrar
MKBrar

Reputation: 13

Vue JS Filter for Title Case

I am absolutely new to Vue JS so please forgive me if my question sounds dumb.

I am learning to create string filters in Vue JS. I was able to convert my string to uppercase using following code.

var app=new Vue({
    el:'#app',
    data:{
        message:'hello world',
    },
    filters:{
        uppercase(value){
            return value.toUpperCase();
        },
    }
})

Now I am trying to make a filter to convert my message to Title Case. eg. hello world to Hello World

I have tried many things like:

filters:{
    upper(value){
        value.toLowerCase().split(' ');
        return value.charAt(0).toUpperCase()+value.slice(1);
    }
}

But I am unable to create a filter correctly. How can we use a for loop inside Vue JS? Or is there any other way to accomplish the Title Case?

Upvotes: 0

Views: 5668

Answers (4)

Thyago Dias
Thyago Dias

Reputation: 161

If the value is in uppercase, you can use it this way:

Vue.filter("TitleCase", value => {
  return value.toLowerCase().replace(/(?:^|\s|-)\S/g, x => x.toUpperCase());
});

Upvotes: 1

Satyam Pathak
Satyam Pathak

Reputation: 6932

Filters/ Mappers, can be simple JS methods who receives some param, apply operation on it and returns a value.

I believe you really don't need a JS method for this,

Try to apply the text-transform CSS style to HTML.

eg: ( text-transform: capitalize );

h1 { text-transform: capitalize; }
<h1>hello world </h1>

Use JS approach when absolutely necessary.

Upvotes: 4

Maximoff
Maximoff

Reputation: 173

filters: {
    titleize(value){
        return value.replace(/(?:^|\s|-)\S/g, x => x.toUpperCase());
    }
}

Upvotes: 8

MKBrar
MKBrar

Reputation: 13

Thanks @skirtle. I used the below code.

    filters:{
     upper(str){
       str = str.toLowerCase().split(' ');

       let final = [ ];

        for(let  word of str){
          final.push(word.charAt(0).toUpperCase()+ word.slice(1));
        }

      return final.join(' ')      
        }
      }

This worked like a charm. :)

Upvotes: 0

Related Questions