2013-03-05 33 views
0

我有一個看起來像搜索字符串,並插入新行的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 

我該怎麼做呢?

回答

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

嘿謝謝 - 是的,逗號實際上不應該在那裏:/ – Andy 2013-03-05 08:36:49

+0

@Andy - 你可以用你想要的任何東西來替換'/,/'或'/ MAN /'。 – 2013-03-05 08:37:35

+1

真棒感謝堆!完全#大腦哈哈,但我會接受你的答案,當計時器允許我! – Andy 2013-03-05 08:39:07

1

使用JavaScript替代方法:

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

如果你要輸出的字符串作爲HTML,使用

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

對於HTML輸出,而不是使用:

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