-1

I have a javascript variable, for example:

var s = "<result>Success</result><name>George</name>";

How can I get with javascript regex the result 'Success' and name 'George'?

Charles
  • 50,943
  • 13
  • 104
  • 142
Maiori
  • 37
  • 9
  • What are you having trouble with? The slash? You can escape it with `\/`, or simply match any character instead with `.`. – Kilian Foth Mar 04 '12 at 17:19
  • @KilianFoth can u show me a real example? I'm not not practical with regex :/ – Maiori Mar 04 '12 at 17:26
  • Is that example typical of your string, or are you actually talking about more complex data structures? –  Mar 04 '12 at 17:29
  • @amnotiam yes, that's is my string or better: "[result]Success[/result][name]George[/name]" i need get 'Success' and 'George' – Maiori Mar 04 '12 at 17:32

2 Answers2

2

You should NOT use regex with XML. Use xml parser http://www.w3schools.com/xml/xml_parser.asp

dotoree
  • 2,983
  • 1
  • 24
  • 29
  • it was an example, the same string can be: var s = "[result]Success[/result][name]George[/name]"; how can I do? – Maiori Mar 04 '12 at 17:21
  • If that's true, you need to work out your consistency issues... and try and keep a standard. – Eric Hodonsky Mar 04 '12 at 17:26
  • 4
    This is an excellent example of the typical Stack overflow answer that doesn't really answer the question – kelloti Mar 04 '12 at 17:33
  • @kelloti Ok then, you should answer the question for [result]Success[/result][name]George[/name] too, cause SuccessGeorge was an "example" – dotoree Mar 04 '12 at 17:43
  • If you noticed, his example wouldn't actually work in an XML parser because there is no parent tag. Hence why I gave him his regex answer. But I still agree, try using an XML parser when possible, so I pointed him toward that also. – kelloti Mar 04 '12 at 17:51
  • It could be wrapped in a parent tag :) – dotoree Mar 04 '12 at 17:56
2

The regex you are looking for is

var result = s.replace(/.*<result>([^<]*)<\/result>.*/, "$1");
var name = s.replace(/.*<name>([^<]*)<\/name>.*/, "$1");

However, as a general rule of thumb - don't ever use regex to parse HTML. The reason is that the browser already has XML parsers built-in, so why use ugly regex to do something the browser already does?

Parsing XML: http://www.switchonthecode.com/tutorials/xml-parsing-with-jquery

Parsing HTML using the DOM: How to parse HTML from JavaScript in Firefox?

Community
  • 1
  • 1
kelloti
  • 8,705
  • 5
  • 46
  • 82