str.split()为每个逗号返回数组和换行符

时间:2017-04-24 09:48:16

标签: javascript typescript ionic2

我正在使用ionic2,typescript / angular2中的对象进行标记。这里是代码。

matchText(array) {
    for (var i = 0; i < 1; i++) {
        var label = this.labels[i];

        var ingredients = label.description.toString().split([',', '(', ')', ' ']);

        let ingredientList: string[] = ingredients;

        console.log('list', ingredientList);

        for (var j = 0; j < ingredientList.length; j++) {
            console.log(ingredientList[j]);
            if (ingredientList[j] == 'SUGAR') {
                this.counter++;
                console.log('Match');
            }
            else {
                console.log('No Match');
            }
        }

        if (this.counter > 0) {
            //this.counter = 0;
            this.navCtrl.push(UnSafePage);
        }
        else {
            this.navCtrl.push(SafePage);
        }
    }
}

上述代码的输出是

INGREDIENTS
WHEAT FLOUR, SUGAR,
CHOCOLATE LIQUOR,
HYDROGENATED VEGETABLE
OIL(SAL FAT, SHEA BUTTER,
RAPESEED OIL, PALM OIL,
SUNFLOWER OIL), WHOLE MILK
POWDER, SHORTENING
(RAPESEED OIL, PALM OIL),
COCOA BUTTER, SALT, BUTTER,
YEAST, EMULSIFIER
(POLYGLYCEROLPOLYRICINOLEATE,
SOY LECITHIN), ARTIFICIAL FLAVOR,
TRISODIUMPHOSPHATE, LEAVENING
(SODIUM BICARBONATE)
CONTAINS: MILK, WHEAT,
SOYBEANS and SHEANUT.
Manufactured in a facility that uses
EGGS and PEANUTS.

我怎样才能得到这个预期的输出?。基本上我想在每个','旁边留一条新线。

INGREDIENTS
    WHEAT FLOUR, 
    SUGAR,
    CHOCOLATE LIQUOR,
    HYDROGENATED VEGETABLE
    OIL(SAL FAT, SHEA BUTTER,
    RAPESEED OIL, PALM OIL,
    SUNFLOWER OIL), 
    WHOLE MILK POWDER, 
    SHORTENING
    (RAPESEED OIL, PALM OIL),
    COCOA BUTTER, 
    SALT, 
    BUTTER,
    YEAST, 
    EMULSIFIER
    (POLYGLYCEROLPOLYRICINOLEATE,
    SOY LECITHIN), 
    ARTIFICIAL FLAVOR,
    TRISODIUMPHOSPHATE, 
    LEAVENING
    (SODIUM BICARBONATE)
    CONTAINS: MILK, 
    WHEAT,
    SOYBEANS and SHEANUT.
    Manufactured in a facility that uses
    EGGS and PEANUTS.

1 个答案:

答案 0 :(得分:1)

查看此JSbin

const mock = 'string , that , you, want, to, split'

const split = mock.split(',');

split.forEach(t => console.log(`${t} \n`))

根据您的需要,您可能希望防止在括号之间使用逗号的换行符。

来自维基百科。

JavaScript使用\(反斜杠)作为

的转义字符
  • \&#39;单引号
  • \&#34;双引号
  • \ backslash
  • \ n新行
  • \ r \ n回车
  • \ t tab
  • \ b退格
  • \ f form feed
  • \ v垂直标签(IE&lt; 9处理&#39; \ v&#39; as&#39; v&#39;而不是垂直标签(&#39; \ x0B&#39;)。如果交叉-browser兼容性是一个问题,使用\ x0B而不是\ v。)
  • \ 0 null character(U + 0000 NULL)(仅当下一个字符不是十进制数字时;否则为八进制转义序列)

**