如何在数组中的字符串中开始新行?

时间:2019-01-03 00:54:09

标签: javascript arrays

我在CodePen(网址:https://codepen.io/hearamsey/pen/ebyLXj)上做了一个随机报价生成器

我在JS的数组中设置了引号,但我希望引号的作者换行。

我尝试在要换行的位置插入\ n:

var quotes = [
"How many cares one loses when one decides not to be something but to be someone. \n -Gabrielle “Coco” Chanel",
"Be who you are and say what you feel, because those who mind don’t matter and those who matter don’t mind. \n -Dr. Seuss",
"Imitation is suicide. \n -Ralph Waldo Emerson", ...]

我希望它显示:

模仿是自杀。
-拉尔夫·沃尔多·爱默生

2 个答案:

答案 0 :(得分:2)

您要通过innerHTML将该字符串作为HTML注入,因此您需要将\n替换为用于在HTML中开始新行的标记,br

document.querySelector('#test').innerHTML = 'BLA BLA <br/> BLA';
<div id="test"></div>

答案 1 :(得分:0)

如果您的quotes数组将是静态的,请尝试从字符串中分离出\n并将其替换为<br/>。否则,您可以将引号数组中的\n手动替换为<br/>

我制作了一个自定义函数checkSeperator,该函数通过将string\n分开并与<br/>联接来返回最终的字符串。

function checkSeperator(str) {
    if (str.includes("\n")) {
        var finalStr = str.split("\n").join(" <br/> ");
        return finalStr;
    } else {
        return str;
    }
}

最终密码:

var quotes = [
    "How many cares one loses when one decides not to be something but to be someone. \n -Gabrielle “Coco” Chanel",
    "Be who you are and say what you feel, because those who mind don’t matter and those who matter don’t mind. <br/> -Dr. Seuss",
    "We must not allow other people’s limited perceptions to define us. \n -Virginia Satir",
    "Don’t look for society to give you permission to be yourself. \n -Steve Maraboli",
    "If things go wrong, don’t go with them. \n -Roger Babson",
    "Wanting to be someone else is a waste of who you are. \n -Kurt Cobain",
    "Tension is who you think you should be. Relaxation is who you are. \n -Chinese Proverb",
    "Where’s your will to be weird? \n -Jim Morrison",
    "Some people say you are going the wrong way, when it’s simply a way of your own. \n -Angelina Jolie",
    "Remember to always be yourself. Unless you suck. \n -Joss Whedon",
    "Do what you can, with what you have, where you are. \n -Theodore Roosevelt",
    "To find yourself, think for yourself. \n -Socrates",
    "If you seek authenticity for authenticity’s sake you are no longer authentic. \n -Jean Paul Sartre",
    "Do what you must, And your friends will adjust. \n -Robert Brault",
    "Just let awareness have its way with you completely.<br/> -Scott Morrison",
    "We must be our own before we can be another’s. <br/> -Ralph Waldo Emerson",
    "This above all: to thine own self be true. <br/> -William Shakespeare"
];

function newQuote() {
    var randomNumber = Math.floor(Math.random() * quotes.length);
    document.getElementById("quoteDisplay").innerHTML = checkSeperator(
        quotes[randomNumber]
    );
}

function checkSeperator(str) {
    if (str.includes("\n")) {
        var finalStr = str.split("\n").join(" <br/> ");
        return finalStr;
    } else {
        return str;
    }
}

您可以将此代码粘贴到js标签中的Codepen中,并且可以使用。