简体   繁体   English

搜索字符串并插入新行javascript

[英]Search string and insert new line javascript

I have a long string that appears like 我有一长串看起来像

var myString = "Bob is the best person in the world MAN John is the best person in the world MAN Peter likes to pick apples daily MAN Fred loves to eat bananas MAN"

What I want to try to do is insert a new line after each MAN - so that I essentially get 我想尝试做的是在每个MAN之后插入新行-这样我就可以

Bob is the best person in the world MAN 
John is the best person in the world MAN 
Peter likes to pick apples daily MAN
Fred loves to eat bananas MAN

How would I go about doing that ? 我将如何去做呢?

myString = myString.replace(/MAN/g, "MAN\n");

/*
 returns
 "Bob is the best person in the world MAN\  (\ means new line)
 John is the best person in the world MAN\
 Peter likes to pick apples daily MAN\
 Fred loves to eat bananas MAN"
*/

Use the javascript replace method: 使用javascript替换方法:

var n=myString.replace(/MAN/g,"MAN\n"); 

If you want to output the string as html, use 如果要将字符串输出为html,请使用

"<br>" instead of "\n".
myString = myString.replace(/MAN/g, "MAN\n");

对于HTML输出,请改用此命令:

myString = myString.replace(/MAN/g, "MAN<br>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM