0

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)
2
  • You can use explode in javascript and get a value in array and you can replace a particular array Commented Oct 9, 2011 at 16:40
  • Do you want the new replaced numbers to increase sequentially? (Also, when asking a question, it is always good to provide a representative example of before and after text.) Commented Oct 9, 2011 at 16:51

4 Answers 4

1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Hi thanks for your answer. The problem is that the replace doesn't seem to be working. The number is fine, I just didn't know whether adding brackets into a string like that would get found properly as its not working
Braces must be escaped within regexps... see my solution above
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[].

Comments

0

Braces must be escaped within regexps...

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

2 Comments

Many thanks for the help, would this find and replace in a string globally?
if you accept his answer, why are you asking? ^^ but yes it will!
0

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.

Comments

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.