I am storing XML in JavaScript variable
<data>
<event>
<eid><![CDATA[152]]]]><![CDATA[></eid>
<start_date><![CDATA[2014年03月01日 00:00:00]]]]><![CDATA[></start_date>
<end_date><![CDATA[2014年03月01日 00:35:00]]]]><![CDATA[></end_date>
<text><![CDATA[New event]]]]><![CDATA[></text>
<rec_type><![CDATA[]]]]><![CDATA[></rec_type>
<event_pid><![CDATA[0]]]]><![CDATA[></event_pid>
<event_length><![CDATA[0]]]]><![CDATA[></event_length>
<event_type><![CDATA[0]]]]><![CDATA[></event_type>
<event_color><![CDATA[#664d0c]]]]><![CDATA[></event_color>
<userid><![CDATA[1]]]]><![CDATA[></userid>
<mediaid><![CDATA[65]]]]><![CDATA[></mediaid>
</event>
</data>
Now I want to replace all such instances
]]><![CDATA[
from variable
I tried this ?
{
var exp = "/]]><![CDATA[/gi";
alert(exp);
return exp;
}
xmldata = xmldata.replace(getExpReg(), "");
But string is not changed what is the issue ?
3 Answers 3
.replace accepts either a string (exact match) or a regex object (regex match). So if you want to use a variable (or function return value) as the arg, you have to do the latter.
Note: the reason your 2ndary issue was that you weren't escaping the square brackets. You must escape characters that have special meaning to the regex engine. Square brackets are used for character classes e.g. [0-9] to match for a number 0 thru 9.
function getExpReg()
{
var exp = new RegExp("\\]\\]><!\\[CDATA\\[","gi");
alert(exp);
return exp;
}
xmldata = xmldata.replace(getExpReg(), "");
Comments
Use a simple regex like
xmldata = xmldata.replace(/\]\]><!\[CDATA\[/gi, "");
In your case you are returning a string literal from the getExpReg method, so the replace method searches for an exact match for the string and replaces its first occurrence.
If you want to use a string literal as a regex, then you need to use RegExp constructor
2 Comments
ignorecase. See the i flag he has put there in his second code block.You haven't escaped the special characters ([,/). Should be:
function getExpReg(){
var exp = /\/\]\]><!\[CDATA\[/gi; // escape using \
alert(exp);
return exp;
}
xmldata = xmldata.replace(getExpReg(), "");
.replaceonly accepts a static string (exact match) or a regex object.var exp = new RegExp(""\]\]><!\[CDATA\[","gi");]]><![cdata[also? You have anignore case flag there...