0

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

1 Answer 1

1

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 '
Sign up to request clarification or add additional context in comments.

4 Comments

Well you would also need to alter the re line with this solution.
Could this be further simplified to str.replace(/^\([0-9]\)$/g, '')?
yep, but you need to put + after the char class and you don't even need a g modifier.
Sorry, it doesn't work I have the string "Main (191)|Health & Beauty (6)|Vision Care (8)" and I need it after replacing to be "Main|Health & Beauty|Vision Care"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.