jsrosetta

Thư viện chuẩn

Regex

RegExp literal của Node.js so với regexp (Go), regex (Rust), Regex literal (Swift) và java.util.regex (Java): replace, test và tìm tất cả match.

Phiên bản tối thiểu
Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.65Swift ≥ 5.7Java ≥ 25
Đã chạy thử trên
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Code Node.js là ES module: lưu file .mjs hoặc đặt "type": "module" trong package.json.

Node.js viết regex bằng literal /pattern/flags ngay trong code. Go không có cú pháp literal cho regex — bạn compile pattern thành *regexp.Regexp bằng regexp.MustCompile, và flag như case-insensitive nằm ngay trong chuỗi pattern ((?i)) thay vì đứng ngoài như /i. Rust dùng crate regex ngoài std, với cú pháp pattern gần như giống hệt Go (cùng họ RE2). Swift có kiểu Regex built-in từ 5.7 với literal /pattern/ ngay trong ngôn ngữ — gần với JS nhất. Java dùng java.util.regex.Pattern/Matcher có từ rất lâu, flag truyền qua tham số thứ hai của Pattern.compile.

Replace, test và tìm tất cả match

let input = 'foobar'
let replaced = input.replace(/foo(.*)/i, 'qux$1')
console.log(replaced) // quxbar
 
let match = /o{2}/i.test(input)
console.log(match) // true
 
input = '111-222-333'
let matches = input.match(/([0-9]+)/gi)
console.log(matches) // [ '111', '222', '333' ]

Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#regex