Xperia Reno
Xperia Reno

Reputation: 531

Javascript : How to put a string into new line if enter key is detected

I have a string like this.

ABC↵XYZ↵PQR

I want every string in new line after ↵

Something like this

ABC

XYZ

PQR

let str = 'ABC↵XYZ↵PQR'

let newString =str.replace(/\n/ig, '');

console.log("New String : " , newString)

Any help would be great.

Thank You.

Upvotes: 0

Views: 299

Answers (3)

Jordy
Jordy

Reputation: 1960

.replaceAll method match for solving this problem.

let str = 'ABC↵XYZ↵PQR'

let newString =str.replaceAll('↵', '\n');

console.log("New String : ");
console.log(newString);

Upvotes: 0

Argee
Argee

Reputation: 1224

If you want to place it in HTML try adding HTML line breaks:

const str = 'ABC↵XYZ↵PQR'

const newString = str.replace(/↵/ig, '<br>');

console.log("New String : ", newString);

const place = document.getElementById('place');

place.innerHTML = newString;
<div id="place"></div>

Upvotes: 1

Balastrong
Balastrong

Reputation: 4464

Isn't this enough?

'ABC↵XYZ↵PQR'.replace(/↵/ig, '\n');

In your example you're just removing any \n (replacing with '') that's why it can't work.

let str = 'ABC↵XYZ↵PQR'

let newString =str.replace(/↵/ig, '\n');

console.log("New String : " , newString)

Upvotes: 0

Related Questions