0

I have an POST AJAX command that returns the following:

`email{[email protected]} cid{215}` 

What I want do is replace the email{} and the cid{} with using only the values as vars

var email = '[email protected]' var customer_id = 215; 

They would appear like that. Is there a cleaner way than:

var result = "email{[email protected]} cid{215}"; // change to [email protected] cid{215} var replace1 = result.replace("email{"); var replace1a = replace1.replace("}"); // change to [email protected] 215 var replace2 = result.replace("cid{"); var replace2a = replace1.replace("}"); // now we have an email, with a space and a number // [email protected] 215 make before space string // this would be email // now make only the int a string called cid 

1 Answer 1

2

First use a regular expression to extract desired data:

var response = "email{[email protected]} cid{215}"; var regex = /email\{(.*)\} cid\{(.*)\}/; var data = response.match(regex); 

Now you can easily obtain values you want:

var email = data[1]; var customer_id = +data[2]; 
Sign up to request clarification or add additional context in comments.

3 Comments

Where can I learn more about regex. Could you explain more. I take .* gets the string value like .htaccess and nginx url rewrites?
@TheBlackBenzKid: start by reading comprehensive MDN
How would I detect spaces. Example Fullname{John Smith Andrew} or Fullname{John Smith}, I am using var regex = /email\{(.*)\} cid\{(.*)\} fullname\{(.*)\}/; but I get the NaN

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.