搜索字符串并插入新行javascript

时间:2013-03-05 08:34:22

标签: javascript

我有一个看起来像

的长字符串
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"

我想要尝试做的是在每个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

我将如何做到这一点?

3 个答案:

答案 0 :(得分:2)

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"
*/

答案 1 :(得分:1)

使用javascript替换方法:

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

如果要将字符串输出为html,请使用

"<br>" instead of "\n".

答案 2 :(得分:1)

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

对于HTML输出,请改用:

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