删除每个换行符后的字符串

时间:2016-07-10 03:15:49

标签: javascript

你好我是javascript的新手,我有一些包含多行的文字。我想在字符'('在每行中断后删除字符串然后用逗号替换所有换行符。这就是我所拥有的到目前为止

var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

var draft = text.replace(/(\r\n|\n|\r)/gm,",");
var final = draft.split('(')[0];
alert(final);

我似乎无法让我的代码给我这个结果:

black gloves,red eyes,solo,short hair

但它仅提供black gloves

6 个答案:

答案 0 :(得分:2)

试试这个:



var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

var draft = text.replace(/(\r\n|\n|\r)/gm," ");
var draft = draft.replace(/(\d)+/gm,",");
var draft = draft.replace(/\(\?\)/gm,"");
alert(draft);




OR



var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

var draft = text.replace(/\(\?\)[ \d\r\n]+/gm,",");
alert(draft);




答案 1 :(得分:1)

您必须知道String.prototype.split()会返回array,在这种情况下,您无需使用它。

您只需使用String.prototype.replace()方法即可达到您想要的效果,如下所示:



var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547";

var draft = text.replace(/(\r\n|\n|\r)/gm, ",").replace(/[^a-zA-Z,]/g, " ").replace(/\s+,/g, ",").trim();
console.log(draft);




答案 2 :(得分:1)

这里有https://jsfiddle.net/loginshivam/724phqag/

var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

var array = text.split("\n");
var val;
for(in=0;in<array.length;in++){
    val=array[in];
    if(in == 0)
       text = val.substring(0, val.indexOf("(")) ;
    else
    text = text  + ","+ val.substring(0, val.indexOf("("));
}

答案 3 :(得分:1)

没有正则表达式:

&#13;
&#13;
var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

var textToArray = text.split('\n');
for(var i = 0; i<textToArray.length; i++) {
    var index = textToArray[i].indexOf('(') - 1;
    textToArray[i] = textToArray[i].slice(0,index);
}
var finalString = textToArray.join(', ');
alert(finalString);
&#13;
&#13;
&#13;

答案 4 :(得分:1)

text.replace(/ \(.\) \d+/g, '').replace(/\r?\n/g, ',')

就像第二行替换一样简单。

var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547";

var final = text.replace(/ \(.\) \d+/g, '').replace(/\r?\n/g, ',');

alert(final);

答案 5 :(得分:1)

备用正则表达式解决方案(https://regex101.com/非常有帮助)。它有点脆,因为它假设每一行格式正确并包含模式。

var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

console.log(text.replace(/ \(\?\) .*(\n|$)/g, ",").slice(0,-1));