Search code examples
javascriptandroidstringtitanium

Get text between two words using javascript


I have a string, it looks like an XML file but actually it is just a normal string saved in a variable.

The string is like this:

<m:properties>
             <d:user_id m:type="Edm.Int64">37</d:user_id>
             <d:organization_id m:type="Edm.Int64">1</d:organization_id>
             <d:name>Test</d:name>
             <d:password>81dc9bdb52d04dc20036dbd8313ed055</d:password>
             <d:email_id>[email protected]</d:email_id>
             <d:user_type_id m:type="Edm.Int32">3</d:user_type_id>
             <d:is_valid m:type="Edm.Boolean">true</d:is_valid>
             <d:registration_date m:type="Edm.DateTime">2012-10-25T11:20:08</d:registration_date>
           </m:properties>

I need to extract text within :

  1. <d:password> </d:password>
  2. <d:email_id></d:email_id>

The content of <d:password> </d:password> and <d:email_id></d:email_id> is dynamic.

How to use javascript String handling functions to extract the required texts?


Solution

  • IF this string is regular (i.e. it's structure never changes), then you could use a regex but, it's awfully close to HTML/XML which are irregular and regex and irregular don't go together. They don't go together so much that if I even suggest a regex, I'll lose all my rep in the downvote storm which would follow. So...

    IF this string is regular, then this is a possible solution for quick and clean:

    String name = text.split(">")[6].split("<")[0];
    String password = text.split(">")[8].split("<")[0];
    

    Here, the magic numbers 6 and 8 are the indices of the tags in your input string. With a little further work, you could lose the magic numbers altogether but if the structure is fixed, constants might work OK for them.

    Or, losing the magic numbers, and perhaps cleaner (although using magic numbers for the length of 'name>' and 'password>').

    String name = text.substring(text.indexof("name>")+5).split("<")[0];
    String password = text.substring(text.indexof("password>")+9).split("<")[0];
    

    Both of these will work for any length of user name and password.

    PS. Of course, the first rule of programming is that there is no such thing as a structure that comes from outside your code which will never change ;)

    PPS. When I say 'any length', that is of course subject to the limits of Java and the Dalvik VM ;)