简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM