javascript - Add a character to each line - Stack Overflow

I have the text in this formatMan like dog.Man like to drink.Man is the kingI want to add a character s

I have the text in this format

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

I want to add a character say ???? to each line in the above text so that the output can look like:

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

Can you help me how to do that?

I have the text in this format

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

I want to add a character say ???? to each line in the above text so that the output can look like:

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

Can you help me how to do that?

Share Improve this question asked Jan 14, 2016 at 19:05 RaghavRaghav 9,6286 gold badges89 silver badges115 bronze badges 3
  • 1 And how these texts are placed in html? – Nikhil Aggarwal Commented Jan 14, 2016 at 19:06
  • Need a little more detail about what this text is. Are these lines in a javascript array? Are they in separate html elements in a web page? All in one HTML element? – Ryan Commented Jan 14, 2016 at 19:08
  • 1 Is it a single string with newline characters or separate strings for each line? – theUtherSide Commented Jan 14, 2016 at 19:09
Add a ment  | 

3 Answers 3

Reset to default 4

You can do this with regular expresion (.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.

Storing the text in an array you can modify each element of the array like this

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'));

assuming you have an input with the string (having newline separators) which you want to process

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

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

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

} );
console.log( newArray );

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745549301a4632490.html

相关推荐

  • javascript - Add a character to each line - Stack Overflow

    I have the text in this formatMan like dog.Man like to drink.Man is the kingI want to add a character s

    10小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信