Giả sử sau đây là chuỗi của chúng tôi -
var sentence = "My Name is David Miller I live in AUS";
Để thay thế khoảng trắng trong chuỗi trên bằng dấu gạch dưới, hãy sử dụng split () cùng với join ().
Ví dụ
Sau đây là mã -
var sentence = "My Name is David Miller I live in AUS";
var withUnderscore = sentence.split(' ').join('_');
console.log("The actual result=")
console.log(sentence);
console.log("After replacing the space with underscore=")
console.log(withUnderscore); Để chạy chương trình trên, bạn cần sử dụng lệnh dưới đây như sau -
node fileName.js
Đây, tên tệp của tôi là demo250.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau trên bảng điều khiển -
PS C:\Users\Amit\javascript-code> node demo250.js The actual result= My Name is David Miller I live in AUS After replacing the space with underscore= My_Name_is_David_Miller_I_live_in_AUS