0

I have a string, which I want to extract the value out. The string is something like this:

cdata = "![CDATA[cu1hcmod6rbg3eenmk9p80c484ma9B]]";          

And I want cu1hcmod6rbg3eenmk9p80c484ma9B. In other words, I want anything inside the ![[CDATA[*]].

I tried to use the following javascript snippet:

cdata = "![CDATA[cu1hcmod6rbg3eenmk9p80c484ma9B]]";
rePattern =    new RegExp("![?:\\s+]]","m");
arrMatch = rePattern.exec( cdata );
result = arrMatch[0];

But the code is not working, I'm pretty sure that it's the way I how specify the matching string that's causing the problem. Any idea how to fix it?

2 Answers 2

4

Your pattern should be something like...

/^!\[CDATA\[(.+?)\]\]$/

Which is...

  1. Match literal starting ![CDATA[.
  2. Lazy match everything up until the closing ] and save it in capturing group $1 (thanks Phrogz for his excellent suggestion).
  3. Match extra ]].

Your string should be available as arrMatch[1].

Sign up to request clarification or add additional context in comments.

8 Comments

I tried something like rePattern = new RegExp("/^!\[CDATA\[([^\]+)\]\]$/","m");, but there is a syntax error.
@Ngu Soon Hui Give me a minute to test it :)
@Ngu, that's a regexp literal, you don't put quotes around it: rePattern = /^!\\[CDATA\\[([^\\]+)\\]\\]$/m;
@NguSoonHui You are missing two backslashes in multiple spots. new RegExp("^\\\[CDATA...
@Phrogz, oops, thanks. Though to be precise, Ngu's comment ate some backslashes and I simply copied it. Fixed now.
|
1

Try this:

var cdata = "![CDATA[cu1hcmod6rbg3eenmk9p80c484ma9B]]";
var regPattern =  /(.*CDATA\[)(.*)(\]\].*)/gm;
alert(cdata.replace(regPattern, "$2"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.