简体   繁体   中英

js replace some string with “\n”

if I have a string that I need to replace every "^^" in the text to break line but with no use for <br> because I am using <texarea> and the <textarea> will display the <br> as a text I wrote some code to do this but this doesn't work

var text="Hello ^^ World ^^ Break ^^ Line",
txt=text.replace(/^^/g,"\n");

who do i fix this?

tnx for helping

You need to escape your ^ , the correct regex would be /\\^\\^/g .

^ otherwise means "starts with" (or "exclude", if it is the first character within square brackets).

 var text=" Hello ^^ World ^^ Break ^^ Line", txt=text.replace(/\\^\\^/g,"\\n"); console.log(txt) 

Another no-regex solution would be splitting up the string and join it again.

 var text="Hello ^^ World ^^ Break ^^ Line", txt=text.split('^^').join('\\n'); console.log(txt); 

Keep in mind that this solution is not as fast as regular expression solutions but it will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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