Friendly Code Friendly Code - 21 days ago 4
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

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)

Code: http://jsfiddle.net/VJYkc/1/

Comments