Cara menggunakan javascript string line break

We can encounter many cases when we have to create a new line using JavaScript. It may seem tricky, but in actuality, these approaches are pretty simple and can be implemented easily. There are other ways to insert new lines with JavaScript. Let's take a look at the most popular ways of creating new lines with JavaScript.

Breaking Strings Using Escape Sequence :

The Escape Sequence used for creating a new line is \n. While displaying some text to the JavaScript console, you can add a new line by using the \n symbol, which stands for a new line. We can add \n with the string of which we want to break the line. Let's See an example of how \n works :

Example : 1

In this example, we will make a string that we want to break. And will print that in the console.

var string = "Hi \nThis is the Second line \nThis is the third line";

console.log(string)

Output :

Hi 
This is the Second line 
This is the third line

Example : 2

We can also use \n Escape sequence with template literals syntax and can get the same results.

var v = `1 \n2 \n3 \n4`;
console.log(v);

Output:

New Line Using Template Literals :

For creating a new line in the console, you can also insert a new line break by pressing Enter while using the template literals. Let's take a look at an example of the same.

Example : 1

Here we are following the template literals syntax to Make our approach possible.

var string = `Hi
This is the Second line 
This is the third line`;

console.log(string)

Output:

Hi 
This is the Second line 
This is the third line

Example : 2

We can also use the combination of entering and \n within the template literal syntax.

var v = `1
2
3\n4`;
console.log(v)

Output :

HTML Break Element :

If we want to add a new line to the Webpage by JavaScript only, then Adding HTML line break elements to your string can do the work for you. By using the break element in the string, we have to use the innerHTML property to render the string as HTML and not the text.

Example : 1

In this example, we are using br tag to break to a new line, this approach reflects the changes in HTML of the page.

 
 
	 
	 
 


Output :

Line No. 1
Line No. 2
Line No. 3
Line No. 4

Example : 2

We can also use the template literal syntax with the JavaScript variable and the result will be the same.

 
 
	 
	 
 

Output :

Accessibility concerns :

Creating line breaks or separate paragraphs using
is a bad practice. It's also a difficulty for people who use screen reading tools to navigate. The presence of the
element may be indicated by screen readers which can be confusing for users and is called not a good practice.


element follows .

Attributes :

Break element's attributes include the global attributes.

Styling with CSS :

The Break element serves a single function it creates a line break in a piece of text. So there is very little you can do to style a line break. You can just add some margin to break elements to increase or decrease space between the lines.

SPLIT(A1, ",")0 - [ OPTIONAL - SPLIT("Alas, poor Yorick"," ")7 by default ] - Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if SPLIT("Alas, poor Yorick"," ")7). If SPLIT("Alas, poor Yorick"," ")5, empty cells values are added between consecutive delimiters.

Karena ini masalah klasik, dimana ketika kita punya string json yang besar biasanya ada masalah saat di decode jadi array.

Salah satu masalah utamanya adalah karena ada line break atau ganti baris, jika string json tersebut di decode dengan fungsi json_decode hasilnya akan error.

Pada tutorial sebelumnya, kita sudah mempelajari Tutorial Belajar JavaScript Bagian 12 : Penjelasan Tipe Data Boolean di JavaScript. Dalam tutorial ini, kitaakan belajar tentang tipe data primitif string dan cara menggunakannya untuk mendefinisikan string.

Pengantar string JavaScript

String JavaScript adalah tipe data primitif. String juga tidak dapat diubah. Artinya, jika Anda memodifikasi sebuah string, Anda akan mendapatkan string baru. String asli tidak berubah.

Untuk membuat tipe data string, Anda menggunakan tanda kutip tunggal (‘) atau tanda kutip ganda (“”) seperti ini:

let str = 'Hai';
let salam = "Halo";

ES6 memperkenalkan literal templat yang memungkinkan Anda menentukan karakter string backtick (`):

let nama = `John`';

Literal templat memungkinkan Anda untuk menggunakan tanda kutip tunggal dan tanda kutip ganda di dalam sebuah string. Sebagai contoh:

let pesan = `"Saya baik". katanya ";

Selain itu, Anda dapat menempatkan variabel dan ekspresi di dalam literal template. JavaScript akan mengganti variabel dengan nilainya dalam string. Ini disebut interpolasi string. Sebagai contoh:

let nama = 'John';
let pesan = `Hai, saya ${nama}.`;

console.log(pesan);

Hasil:

Hai, saya John.

Dalam contoh ini, JavaScript mengganti variabel nama dengan nilai yang sudah ditentukan dalam variabel sebelumnya.

Mengatasi masalah karakter khusus

Untuk mengatasi masalah karakter khusus, Anda bisa menggunakan karakter \ backslash. Sebagai contoh:

  • Windows line break : ‘\r\n’
  • Unix line brek: ‘\n’
  • Tab: ‘\t’
  • Backslash ‘\’

Contoh berikut menggunakan karakter garis miring terbalik untuk menghindari karakter kutip tunggal dalam sebuah string:

let str = 'Sekarang adalah hari Jum’\at';

Menghitung panjang string

Properti length mengembalikan nilai panjang sebuah string:

let str = "Selamat Pagi!";
console.log(str.length); // 13

Perhatikan bahwa JavaScript memiliki tipe String (dengan huruf S dalam huruf besar), yang merupakan tipe pembungkus dari tipe data primitif string. Oleh karena itu, Anda dapat mengakses semua properti dan metode tipe String dari tipe data primitif string.

Mengakses karakter

Untuk mengakses karakter dalam string, Anda menggunakan notasi [] seperti array dengan nilai indeks awal nol. Contoh berikut mengembalikan karakter pertama string dengan indeks nol:

let str = "Halo";
console.log(str[0]); // "H"

Untuk mengakses karakter terakhir dari string, Anda menggunakan length – 1 indeks:

let str = "Halo";
console.log(str[str.length -1]); // "o"

Menggabungkan string melalui operator +

Untuk menggabungkan dua atau lebih string, Anda bisa menggunakan operator + :

let nama = 'John';
let str = 'Halo' + nama;
console.log(str); // "Halo Yohanes"

Jika Anda ingin membentuk string sepotong demi sepotong, Anda dapat menggunakan operator += :

let nama = `John`';
0

Hasil:

let nama = `John`';
1

Mengubah nilai menjadi string

Untuk mengonversi nilai non-string menjadi string, Anda menggunakan salah satu dari berikut ini:

  • String(n);
  • ” + n
  • n.toString()

Perhatikan bahwa metode toString() tidak berfungsi untuk undefined dan null.

Saat Anda mengonversi string menjadi boolean, Anda tidak dapat mengonversinya kembali. Sebagai contoh:

let nama = `John`';
2

Dalam contoh ini:

  • Pertama, deklarasikan variabel status dan inisialisasi dengan nilai false.
  • Kedua, ubah variabel status menjadi string menggunakan metode toString().
  • Ketiga, ubah string kembali ke nilai boolean menggunakan fungsi Boolean(). Fungsi Boolean() mengubah string “false” menjadi nilai boolean. Hasilnya benar karena “false” adalah string yang tidak kosong.

Perhatikan bahwa nilai string Boolean() yang mengembalikan nilai false, adalah string kosong (”);

Membandingkan string

Untuk membandingkan dua string, Anda menggunakan operator pembanding seperti >, >=, <, <=, dan == operator.

Operator pembanding membandingkan string berdasarkan nilai numerik karakter. Dan itu mungkin mengembalikan urutan string yang berbeda dari yang digunakan dalam kamus. Sebagai contoh:

let nama = `John`';
3

Namun :

let nama = `John`';
4

Kesimpulan :

  • String JavaScript adalah nilai primitif dan tidak dapat diubah.
  • String literal dibatasi oleh tanda kutip tunggal (‘), tanda kutip ganda (“), atau backticks (`).
  • Properti length mengembalikan nilai panjang string.
  • Gunakan operator pembanding `>, >=, <, <=, == untuk membandingkan string.

Itu dia tutorial penjelasan tipe data string dalam JavaScript. Semoga tutorial ini membantu Anda untuk memahami jenis data string dalam JavaScript.