JavaScript/regex: Hapus teks di antara tanda kurung
Apakah mungkin untuk mengubah
Hello, this is Mike (example)
ke
Hello, this is Mike
menggunakan JavaScript dengan Regex?
Jawaban #1
"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, "");
Hasil :
"Hello, this is Mike"
Jawaban #2
var str = "Hello, this is Mike (example)";
alert(str.replace(/\s*\(.*?\)\s*/g, ''));
Itu juga akan mengganti spasi berlebih sebelum dan sesudah tanda kurung.
Jawaban #3
Coba / \([\s\S]*?\)/g
Di mana :
(spasi) mencocokkan karakter (spasi) secara harfiah
\( mencocokkan karakter ( secara harfiah
[\s\S] mencocokkan karakter apa pun (\s mencocokkan karakter spasi apa pun dan \S mencocokkan karakter bukan spasi apa pun)
*? mencocokkan antara nol hingga tak terbatas kali
\) mencocokkan karakter ) secara harfiah
g cocok secara global
Contoh Kode:
var str = "Hello, this is Mike (example)";
str = str.replace(/ \([\s\S]*?\)/g, '');
console.log(str);.as-console-wrapper {top: 0}