0
  1. How to use a regular expression to match this string: <div><span>regular</span><span>expression</span></div>.

  2. How to exchange the first span of the contents and the contents of the second span.

In my opinion, it can use jquery source code.

csu
  • 1
  • 1
  • 4
    show your attempts.... – Avinash Raj Aug 27 '14 at 10:03
  • Welcome to Stack Overflow! Here is a nice tool to test regexps online: http://www.regexr.com/39d2p. You should first try by yourself before asking on Stack Overflow, so that you can provide what you tried and what did not work. Hint: jQuery won't be necessary for this job ;) – sp00m Aug 27 '14 at 10:07
  • Match that string exactly? Your question needs more details. – Evan Knowles Aug 27 '14 at 10:08

1 Answers1

1

Make sure you read RegEx match open tags except XHTML self-contained tags

Then the solution to you problem would be:

var str = '<div><span>regular</span><span>expression</span></div>';

var newString = 
    str.replace(
        /(<div><span>)([^<]*)(<\/span><span>)([^<]*)(<\/span><\/div>)/i,
        '$1$4$3$2$5'
); // where /[^<]*/ matches anything but '<'

// results in "<div><span>expression</span><span>regular</span></div>"

Whitespace-safe regex:

/(<\s*div\s*>\s*<\s*span\s*>)([^<]*)(<\/\s*span\s*>\s*<\s*span\s*>)([^<]*)(<\/\s*span\s*>\s*<\/\s*div\s*>)/i

But honestly this is just a vague answer to you vague question and might need a bit more jQuery :)

Community
  • 1
  • 1
Matyas
  • 13,473
  • 3
  • 60
  • 73
  • More generic would be `str.replace(/(
    )([^<]+)(<\/span>)([^<]+)(<\/span><\/div>)/,'$1$4$3$2$5')`
    – e666 Aug 27 '14 at 10:18
  • Thank you @e666, I overlooked that they have to be swapped and not exchanged + the idea of not hardcoding the values. Updated answer – Matyas Aug 27 '14 at 10:21