fuzzy dunlop
fuzzy dunlop

Reputation: 477

how to parse string

im trying to parse the following string;

"data[Product][0][fieldname]"

i need to be able to change the "[0]" part to a number, the "data[Product]" wont change while the "[fieldname]" will change.

im not sure how to do it with javascript but have an rough idea.

all i have which is wrong, is below but since [0] varies each time it doesnt work;

name="data[Product][0][fieldname]";
name.replace('[0]', '['+newrowid+']'

Jsfiddle; http://jsfiddle.net/fuzzy_dunlop/8WKcs/

Upvotes: 0

Views: 575

Answers (4)

rnalexander
rnalexander

Reputation: 76

Replace can take a regular expression instead of a string.

Try this:

name="data[Product][0][fieldname]";
name.replace(/\[\d\]/, '['+newrowid+']');

Upvotes: 1

Konerak
Konerak

Reputation: 39773

Use a regexp:

var a = "data[Product][0][fieldname]";
var re = /(.*\[.*\]\[)(.*)(\]\[.*\])/gi;  

newstr = a.replace(re, "$1" + "YourString" + "$3");  
document.write("Now: " + newstr); 

Example code: http://jsfiddle.net/NKbd9/1/

Upvotes: 5

t0s6i
t0s6i

Reputation: 171

Use this instead

name = name.replace('[0]', '['+newrowid+']');

Upvotes: 1

GillesC
GillesC

Reputation: 10874

I assume you are trying to do this inside a loop, in that case you just need to make it dynamic. Also not that replace doesn't change the current string, it returns a new string so you need to assign the value returned back to name.

    var i = 0, 
        len = 10,
        name,
        newrowid = 13;
for(; i <len; i++) {
    name = "data[Product]["+i+"][fieldname]";
    name = name.replace('['+i+']', '['+newrowid+']');
}

Upvotes: 0

Related Questions