Computer >> Máy Tính >  >> Lập trình >> Javascript

JavaScript Regex để xóa văn bản sau dấu phẩy và từ sau?

Giả sử sau đây là chuỗi của chúng tôi -

var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);

Chúng ta cần xóa văn bản sau dấu phẩy và từ sau, tức là sau khi xóa "Tôi sống ở Hoa Kỳ" và giữ phần còn lại. Đây sẽ là chuỗi kết quả -

My Name is John, Smith

Đối với điều này, hãy sử dụng match () cùng với split ().

Ví dụ

var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);
var expression = sentence.match(/([^,]*)(.*)/)[1];
var positionForComma = sentence.match(/([^,]*),(.*)/)[2].split(' ')[1]
var newValue = expression + ', ' + positionForComma
console.log("Updated="+newValue);

Để chạy chương trình trên, bạn cần sử dụng lệnh sau -

node fileName.js.

Đây, tên tệp của tôi là demo175.js.

Đầu ra

Điều này sẽ tạo ra kết quả sau -

PS C:\Users\Amit\javascript-code> node demo175.js
The original value=My Name is John, Smith I live in US
Updated=My Name is John, Smith