Friendly Code Friendly Code - 1 year ago 142
Javascript Question

Javascript RegExp find and replace empty square brackets

I have a string that contains something like name="text_field_1[]" and I need to find and replace the '1[]' part so that I can increment like this '2[]', '3[]' etc

Here is the code:

$search = new RegExp('1[]', 'g');
$replace = $number + '[]';
$html = $html.replace($search, $replace)

Answer Source

You can use \d in your regexp whitch means that onlu numbers used before []. Also you need to escape [] because of it's special characters in regexp.

$search = new RegExp('\\d+\\[\\]', 'g');
$replace = $number + '[]';
$html = $html.replace($search, $replace)


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download