Dylan Cross
Dylan Cross

Reputation: 5986

jQuery/JavaScript regex return matched text from string

I am trying to create a fairly complex system for my website. I want to be able to write some pseudo like code and then parse it to make it do something in my back-end.

My data is inside two $.each loops as this is an Object of data with multiple levels to it.

For instance, I want to take a string like this:

"<!this!> == <!PropertyStreetNumber!>"

Then how I would like for the above code to executed is this:

FormData[parentKey][this] == FormData[parentKey]["PropertyStreetNumber"]

Thanks for any help!

Here's some of my code, the code where this would need to go in (see commented area) http://jsbin.com/liquvetapibu/1/

Upvotes: 0

Views: 62

Answers (3)

Alvaro Montoro
Alvaro Montoro

Reputation: 29635

Is there any restriction not to use regular expressions on JavaScript?

You could do something like this:

var myString = "<!this!> == <!PropertyStreetNumber!>";
var aux = /<!(.*?)!> == <!(.*?)!>/.exec(myString);

The value of aux will be an array with 3 elements:

  1. The string that was tested.
  2. The first element within <! !>
  3. The second element within <! !>

Then it would depend on what the content on each one is: in your example this is an object, while you seem to use PropertyStreetNumber as a string (maybe a typo?). If you want to use it as an object, you will have to use eval() (e.g.: eval(aux[1])) while if you want to use it as a string, you can use it directly (e.g.: aux[2]).

Upvotes: 1

Santiago Rebella
Santiago Rebella

Reputation: 2449

you could try with

var beg = str.indexOf("== <!") + 5;

to find the index of the beggining and then slice counting the chars from beginning like

str.slice(beg, -2);

and from there build the rest.

couldnt that work?`

Upvotes: 0

jwatts1980
jwatts1980

Reputation: 7346

Conceptually, the first thing you would need to do is determine the type of statement you are working with. In this case, a comparison statement. So you need a regex statement to filter this into a "statement type".

Once you do that, you can figure out what the arguments are. So you create a regex to pull out the arguments on each side of the operator.

Next, the strings that represent action code items need to be parsed. The this argument is actually an object, whereas "PropertyStreetNumber" is a string. You've got to be able to determine which is which. Then you can filter that into a function that has been created specifically to handle those statements types.

If at all possible, I would try to avoid the use of eval(). You can get into trouble with it.

Upvotes: 0

Related Questions