为每一行添加一个字符

时间:2016-01-14 19:05:43

标签: javascript

我有这种格式的文字

 Man like dog.
 Man like to drink.
 Man is the king

我想添加一个字符说????到上面文本中的每一行,以便输出看起来像:

 ????Man like dog.
 ????Man like to drink.
 ????Man is the king

你能帮我怎么做吗?

3 个答案:

答案 0 :(得分:2)

将文本存储在数组中,您可以像这样修改数组的每个元素

var text = ['Man like dog.', 'Man like to drink.', 'Man is the king.'];

console.log(text.join('\n'));

text = text.map(function(element){ return '????' + element;});

console.log(text.join('\n'));

答案 1 :(得分:0)

您可以使用常规表达式(.replace(/^/gm, '????'))执行此操作:

> str = "Man like dog.\nMan like to drink\nMan is the king."
'Man like dog.\nMan like to drink\nMan is the king.'
> str = str.replace(/^/gm, '????')
'????Man like dog.\n????Man like to drink\n????Man is the king.'
> console.log(str)
????Man like dog.
????Man like to drink
????Man is the king.

答案 2 :(得分:0)

假设您输入了要处理的字符串(具有换行符分隔符)

var array = input.split(/\n/);

var newArray = [];
array.forEach( function(element){

   newArray.push( "????" + element );

} );
console.log( newArray );