PASSWORD RESET

Your destination for complete Tech news

Vue

How to convert a string to an array in Vue JS?

834 0
< 1 min read

In Vue, you can convert a string to an array using the split() method, which splits a string into an array of substrings based on a specified separator. Here’s an example of how to convert a string to an array in Vue:

<template>
  <div>
    <p>Original string: {{ originalString }}</p>
    <p>Array: {{ stringArray }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      originalString: 'apple, banana, cherry',
    };
  },
  computed: {
    stringArray() {
      return this.originalString.split(', ');
    },
  },
};
</script>

In this example, we have a string originalString containing a list of fruits separated by commas and spaces. We’re using a computed property called stringArray to convert this string to an array using the split() method with the separator ', '. This creates an array stringArray containing the individual fruit names as separate array elements. Finally, we’re displaying both the original string and the resulting array using interpolation in the template.

Note that you can use any separator in the split() method, depending on your needs. For example, if your string elements are separated by a different character or string, you can pass that separator as an argument to the split() method. If your string contains no separator, you can split it into individual characters using the empty string '' as the separator.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.