开发者

Javascript RegExp find and replace empty square brackets

开发者 https://www.devze.com 2023-04-11 23:57 出处:网络
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.

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.

Code:

$search = new RegExp('1[]', 'g')开发者_运维技巧;
$replace = $number + '[]';
$html = $html.replace($search, $replace)


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/


You can use callbacks.

var $counter = 0;

$html = $html.replace(/1\[\]/g, function(){
    ++$counter;
    return $counter+'[]';
});

If you need [] preceded by any number, you can use \d:

var $counter = 0;
$html = $html.replace(/\d\[\]/g, function(){
    ++$counter;
    return $counter+'[]';
});

Note:

  • escape brackets, because they are special in regex.
  • be sure that in $html there is only the pattern you need to replace, or it will replace all 1[].


Braces must be escaped within regexps...

var yourString="text-field_1[]";
var match=yourString.match(/(\d+)\[\]/);
yourString=yourString.replace(match[0], parseInt(match[1]++)+"[]");


Here's something fun. You can pass a function into string.replace.

  var re = /(\d+)(\[\])/g/;
  html = html.replace(re, function(fullMatch, value, braces) {
    return (parseInt(value, 10)+1) + braces;
  }

Now you can replace multiple instances of #[] in your string.

0

精彩评论

暂无评论...
验证码 换一张
取 消