Andy
Andy

Reputation: 19251

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

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 ?

Upvotes: 0

Views: 64

Answers (3)

ohaal
ohaal

Reputation: 5268

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

For HTML output, use this instead:

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

Upvotes: 1

SteveP
SteveP

Reputation: 19093

Use the javascript replace method:

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

If you want to output the string as html, use

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

Upvotes: 1

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

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

Upvotes: 2

Related Questions