Read line break in a string with JavaScript
Possible Duplicate:
Replace all line break in a string with <br /> tag in javascript
How can I read the line break from a value with JavaScript and replace it with a <br />
tag?
Example:
var a = "This is man.
Man like dog."
I would like my result to look something like
var a = "This is man.<br />Man like dog.";
var newString=oldString.replace(/n/g,"<br />");
要完成:我遇到了' n'不起作用的情况,在我使用的情况下:
someString.replace(/n/g,'<br />')
.replace(/r/g,'<br />')
.replace(/rn/g,'<br />');
+1 for Click Upvote's answer. I'd just point out that using that style of defining strings, you'll have a heap of extra whitespace in there. Doing a simple replace of the newline will actually give you this string:
"This is man.<br /> Man like dog."
The basic solution is to change your replace function:
newString = oldString.replace(/ns*/g, "<br />");
Or even better (IMHO), define your strings like this:
var a = "This is man.n"
+ "Man like dog."
;
It means you can still get nice indenting without the extra overhead being added into your variables, plus, it allows you to add comments easily:
var a = "This is man.n" // this is the first line.
+ "Man like dog." // and woo a comment here too
;
链接地址: http://www.djcxy.com/p/88878.html
上一篇: 如何将图像添加到JPanel?