简体   繁体   中英

JavaScript regex to replace a specific word with a line break

I have a number of strings coming back from the database and I need to separate them into 2 lines based on a specific word that the backend person can insert in the string. (The word or symbol can be anything.)

I have tried the following:

    var str = "some string some string space some string";
    str = str.replace(/space/g, "\n")
    console.log(str);

but the string still appears over one line only.

...

        var str = "some string some stringspacesome string";
        str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
        console.log(str);
        var screenHeight = (this.state.windowHeight -90) + 'px';
        return (
            <div>
                <Header />
                <section className={"main " + this.state.color_name} style={{minHeight: screenHeight}}>
                    <div className="content-wrapper">
                        <div className="content" >
                        <h1>{str}</h1>

...

After the replacement, the str variable is going to be used as the contents of an h1 element.

If you want the string to be used as the contents of an HTML tag, then \\n isn't the proper way to have it display on two lines. Rather, you'll need to use an html break tag of <br/> . You can either replace that into your strings, like this:

str = str.replace(/space/g, "<br/>")

Or for simplicity's sake, since you mentioned that the "space" string to replace can be anything, it seems like you could just skip the replacement altogether and use the desired replacement on the backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM