Andrew_Nady
Andrew_Nady

Reputation: 91

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, '');
}

Upvotes: 0

Views: 126

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

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 '

Upvotes: 1

Related Questions