How to remove `//<![CDATA[` and end `//]]>` with javascript from string?

后端 未结 3 1122
一个人的身影
一个人的身影 2021-01-17 18:40

How to remove // and end //]]> with javascript from string?

var title = \"

        
相关标签:
3条回答
  • 2021-01-17 18:57

    You can use the String.prototype.replace method, like:

    title = title.replace("<![CDATA[", "").replace("]]>", "");
    

    This will replace each target substring with nothing. Note that this will only replace the first occurrence of each, and would require a regular expression if you want to remove all matches.

    Reference:

    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
    0 讨论(0)
  • 2021-01-17 19:04

    You ought to be able to do this with a regex. Maybe something like this?:

    var myString = "<![CDATA[A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks]]>";
    var myRegexp = /<!\[CDATA\[(.*)]]>/;
    var match = myRegexp.exec(myString);
    alert(match[1]);
    
    0 讨论(0)
  • 2021-01-17 19:10

    I suggest this wider way to remove leading and trailing CDATA stuff :

    title.trim().replace(/^(\/\/\s*)?<!\[CDATA\[|(\/\/\s*)?\]\]>$/g, '')
    

    It will also work if CDATA header and footer are commented.

    0 讨论(0)
提交回复
热议问题