Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split commas in string to <br /> in JSX

I have a string (an address) containing commas that I wish to delimit to line-breaks inside some JSX. Doing the following merely outputs the <br /> as a string:

{address.split(',').join('<br />')}

How can I do what I need to do, preferably retaining the commas?

like image 232
hamishtaplin Avatar asked Nov 06 '15 10:11

hamishtaplin


People also ask

How do you convert a string separated by a comma to an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How Split Comma Separated Values in HTML?

To convert comma separated text into separate lines, you need to use trim() along with split() on the basis of comma(,).

How do you split a comma in JavaScript?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.


4 Answers

You can try wrap each address in p tag and don't use <br />,

var Component = React.createClass({
    render: function() {
        var addresses = this.props.addresses.split(',').map(function (address, index) {
            return <p key={index}>{ address }</p>; 
        });

        return <div className="addresses">{addresses}</div>;
    }
});

Example

like image 105
Oleksandr T. Avatar answered Oct 28 '22 12:10

Oleksandr T.


To delimit based on commas, turning commas into line-breaks, while "preferably retaining the commas" (not sure you meant you want to retain them in the output, but interpreting that as such) you can try the following (works for me):

let newAddress = address.split(',').map(line => <span>{line},<br/></span>);
// span tag here only in order for JSX to accept br tag
like image 32
Dan Kurth Avatar answered Oct 28 '22 13:10

Dan Kurth


You can simply insert <br/> between the lines via reduce:

{address.split(',').reduce((all, cur) => [
  ...all,
  <br/>,
  cur
])}
like image 4
Del Oracle Avatar answered Oct 28 '22 11:10

Del Oracle


Sometimes you want to use line breaks and not paragraphs. In that case, you can do:

function convertNewLines(_text) {
    let lines = _text.split('\n');
    let elements = [];
    for (let i=0; i<lines.length; i++) {
        elements.push(lines[i]);
        if (i < lines.length-1) {
            elements.push(<br key={i}/>);
        }
    }
    return elements;
}

This avoids the use of dangerously setting inner HTML.

(FWIW I figured this out by using the Babel REPL.)

like image 1
Jurie Horneman Avatar answered Oct 28 '22 13:10

Jurie Horneman