This is a short tutorial on how to convert string to array in react example. It includes how to convert a string with a delimiter to an array using the split() function.
Suppose we have a string as an input.
var mystr="This is an string"
And output converted to Array
["this","is","an","string"]
In javascript, We have a string split() function. It is used to split the string into an array of words.
here is a syntax
string.split(delimiter)
by default, the delimiter is space, can include a comma(,), hyphen(-), and any character.
In real-time, We have an object coming from API.
this object contains the property of a string which we need to convert to an array to render in a component in react.
Let’s see examples with different delimiter spaces or commas in react.
How to convert string to an array with spaces in react javascript
This example converts strings stored in react state into an array.
- store the string in react state
- In the Render method, Convert string into an array with delimiter space using the split method.
- Finally, render an array using map iteration as an ordered list on a component
Example:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
interface AppProps {}
interface AppState {
name: string;
}
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
this.state = {
name: 'This is an string'
};
}
render() {
let str = this.state.name;
var myarray = str.split(' ');
console.log(myarray);
let result = myarray.map(item => <li>{item}</li>);
return (
<div>
<ul>{result}</ul>
</div>
);
}
}
How to convert string with comma delimiter into Array in react
This is an example for converting fullnames into the array of first, last, middle names.
- Let’s store the full names in string delimiter in react component state
- Convert string into an array using string delimiter
- Finally, prints the array of strings in to render using the map function
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
interface AppProps {}
interface AppState {
name: string;
}
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
this.state = {
name: 'firstName, lastName, middleName'
};
}
render() {
let fullname = this.state.name;
var names = fullname.split(',');
let result = names.map(item => <li>{item}</li>);
return (
<div>
<ul>{result}</ul>
</div>
);
}
}
render(<App />, document.getElementById('root'));
Conclusion
In this example, Converted string into an array with space or delimiter using array split function in react with example