Convert Camelcase strings to kebab-case

Asked

Viewed 113 times

1

I have a list of buttons...

<button @click="chamaEstilo($event)" :data-el="index" class="buttonEstilo" v-for="(item, index) in filteredList" :key="index" v-if="verificaRestricao(item)" >
    {{index}}
</button>

I’d like you to print out the {{index}} in the formatting pattern of HTML tags for components, that is, if you send a string with the value fontsize should print font-size and so for all occurrence of maíusculas...

  • Index prints css properties, some with the name in camelCasel, example, (borderLeft, fontsize) wanted to print them normally (border-left, font-size)

1 answer

4


I think what you want is to convert strings into Camelcase for kebab-case,

you can do it like this:

function camelCaseToKebabCase(str) {
  return str.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase()
}

const testes = ['fooBar', 'kebab-case', 'fontSize'];
console.log(testes.map(camelCaseToKebabCase));

/* resultado:
[
  "foo-bar",
  "kebab-case",
  "font-size"
]
*/

and use a filter for this in Vue and the template:

<button @click="chamaEstilo($event)" :data-el="index" class="buttonEstilo" v-for="(item, index) in filteredList" :key="index" v-if="verificaRestricao(item)" >
    {{index | camelCaseToKebabCase}}
</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.