Sadikhasan
Sadikhasan

Reputation: 18601

Extract portion of string jQuery

<input type="text" name="data[546c8157fcc404ca04951022][5476bddb4a1bfef2128b4567][exp][apr]">

I want to extract second part of array and replace with 0. how can do this?

Expected output

<input type="text" name="data[546c8157fcc404ca04951022][0][exp][apr]">

I tried replace and substring function but no luck. Please help me.

Upvotes: 0

Views: 41

Answers (2)

hsz
hsz

Reputation: 152304

Try with:

var element =  $('<input type="text" name="data[546c8157fcc404ca04951022][5476bddb4a1bfef2128b4567][exp][apr]">');

var parts = element.attr('name').split('][');
    parts[1] = 0;

element.attr('name', parts.join(']['));

Output:

<input type="text" name="data[546c8157fcc404ca04951022][0][exp][apr]">

Upvotes: 1

vks
vks

Reputation: 67988

^(.*?\[[^\]]+\])\[[^\]]+\]

Try this.Replace by $1[0].See demo.

http://regex101.com/r/yR3mM3/47

var re = /^(.*?\[[^\]]+\])\[[^\]]+\]/gi;
var str = '<input type="text" name="data[546c8157fcc404ca04951022][5476bddb4a1bfef2128b4567][exp[apr]">';
var subst = '$1[0]';

var result = str.replace(re, subst);

Upvotes: 1

Related Questions