简体   繁体   中英

Regular Expression: replace string in javascript

I want a regular expression to match a string like this "(192)"

the string starts with "(" and ends with ")" and numbers from 0 to 9 go between the parentheses.

I've tried this function before but it does not work:

function remove_garbage_numbers(str) {
    var find = '^\([0-9]\)$';
    var re = new RegExp(find, 'g');

    return str.replace(re, '');
}

You don't need to pass this to RegExp constructor. And you don't need to have a g modifier when anchors are used. And aso when anchors are used, it's safe to use m multiline modifier.

var find = /^\([0-9]+\)$/m;

ie,

function remove_garbage_numbers(str) {
    var re = /^\([0-9]+\)$/m;
    return str.replace(re, '');
}

OR

var re = new RegExp("^\\([0-9]+\\)$", 'm');

ie,

function remove_garbage_numbers(str) {

    var re = new RegExp("^\\([0-9]+\\)$", 'm');

    return str.replace(re, '');
}

Update

> "Main (191)|Health & Beauty (6)|Vision Care (8)".replace(/\(\d+\)/g, "")
'Main |Health & Beauty |Vision Care '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM