最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add a character to each line - Stack Overflow

programmeradmin1浏览0评论

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 );
发布评论

评论列表(0)

  1. 暂无评论