Daniel Harris
Daniel Harris

Reputation: 1905

How do I replace a character between the last occurrence of two characters in a string in JavaScript?

I have an input text field named d[hotel][suite][0]. How would I replace the last [0] with [1] or [2] and so on? Is this possible using jQuery or would I have to use the replace function with regex?

What I've tried so far:

the_name = $(this).attr('name');
the_name = the_name.replace(/[.*]/, '2');

Didn't work

the_name = $(this).attr('name');
var start_pos = the_name.lastindexOf('[') + 1;
var end_pos = the_name.lastindexOf(']',start_pos);
var text_to_replace = the_name.substring(start_pos,end_pos);

Doesn't work with 2+ digits.

Any help would be appreciated.

Upvotes: 0

Views: 44

Answers (1)

Barmar
Barmar

Reputation: 782499

This is probably easier using a regexp.

new_name = the_name.replace(/\[(\d+)\]$/, function(match, n) {
    return '[' + (parseInt(n, 10)+1) + ']');
});

The $ anchor in the regexp makes it match the brackets at the end. When you use a function as the replacement, it calls the function with the matched string and each of the capture groups as arguments, and whatever it returns is used as the replacement.

Upvotes: 5

Related Questions