-1

This question is quite different with How do I use the Enter key as an event handler (javascript)? or Prevent form submission on Enter key press

I just want to use a JavaScript function to replace Enter Key Event.

For example, now I am typing this string into a textarea

"Hello world Hello world Hello world"

As you can see there are three "Hello world" in this string.

If I want to make this string to this effect

"Hello world

Hello world

Hello world"

I should press the Enter key after every "Hello world".

Now this question is how to use JavaScript to replace the Enter Key Event? It means the user doesn't need to press the Enter key and the scripts would do it automatically.

And also I hope that the scripts would cross different browsers.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CashLee李秉骏
  • 1,038
  • 1
  • 10
  • 23

2 Answers2

2

if you're in a textarea or a pre, you could split them using \r\n newline marker. Else, you could simply add a <br> tag.

var myString = "Hello world, Hello world, Hello world".split(',').join('\r\n');
$('textarea').text( myString );

Of course, you'll get the string via JS ($('textarea').text()), and I guess you'll want to use a RegExp inside the split method.

Example: http://jsbin.com/eqekir/1/edit

Simon Boudrias
  • 42,953
  • 16
  • 99
  • 134
  • It is not the final effect that I want.I just want to use javascript to simulate keyboard event.And '\r\n' wouldn't be in added into the string. :-( – CashLee李秉骏 Nov 13 '12 at 03:45
  • Hi, without more detail it's going to be hard to help you. I've made an example here so you can check out: http://jsbin.com/eqekir/1/edit Using `\r\n` work just fine as I showed you in my answer. I feel your problem now reside inside the logic you want to put in your script. – Simon Boudrias Nov 13 '12 at 04:52
  • Thank you very much ... I have solved my problem with your answer. – CashLee李秉骏 Nov 13 '12 at 06:39
  • Would you like to vote my question?!I don't know why it would be vote down.Besides,is there a way that I can use javascript to simulate a keyboard event? :-) – CashLee李秉骏 Nov 13 '12 at 06:41
  • You can't use javascript to simulate a keyboard event in the way you meant it in your question. Although, you can trigger events, but those will only get catched by the `eventListener` you added via javascript. For example, in jQuery `$('a').trigger('click')` will not open the link, but it will trigger any event you added via `$('a').on('click', /* do something */ )` – Simon Boudrias Nov 13 '12 at 15:22
-1

You can do something like

console.log("This is a \n new line");

That would make new line appear on a new line. You could use a regular expression to separate the

CWitty
  • 4,488
  • 3
  • 23
  • 40