【问题标题】:Remove single quotes from beginning and end of string从字符串的开头和结尾删除单引号
【发布时间】:2017-11-01 02:55:39
【问题描述】:

我正在尝试从原始文本变量中删除单引号并通过 AJAX 发布。

我在从 API 端点返回时收到此错误:Invalid document: Content is not allowed in prolog

当您的 XML POST 数据前面有 ""'' 通常与我的情况一样,会导致此错误。因此,您所要做的就是使用一些简单的正则表达式和.trim.replace 删除第一个和最后一个""''

无论出于何种原因,它都不会为我移除它。我在网上尝试了无数的正则表达式示例,据说它们修剪了第一个和最后一个字符,如果它们是""'',则只修剪第一个和最后一个字符,但没有任何成功。

代码:

$('#idealMatBtn').click(function (e) {
    var xmlSTR = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd"><cXML timestamp="2015-06-12T08:30:00" xml:lang="en-US"> <Header> <From> <Credential domain="NetworkID"> <Identity>EU019985</Identity> </Credential> </From> <To> <Credential domain="DUNS"> <Identity>Ideal Supply Test</Identity> </Credential> </To> <Sender> <Credential domain="NetworkID"> <Identity>Ideal Supply Test</Identity> <SharedSecret>Ideal</SharedSecret> </Credential> <UserAgent>eProcurement-System 1.0</UserAgent> </Sender> </Header> <Request> <PunchOutSetupRequest operation="create"> <BuyerCookie>[Unique-Generated-Identifier-from-eProcurement-System]</BuyerCookie> <Extrinsic name="FirstName">John</Extrinsic> <Extrinsic name="LastName">Smith</Extrinsic> <Contact role="endUser"> <Name xml:lang="en-US">john</Name> <Email>smith+john@greenwingtechnology.com</Email> </Contact> <BrowserFormPost> <URL>https://test-sys.greenwingtech-system.com/punchout/return</URL> </BrowserFormPost> </PunchOutSetupRequest> </Request></cXML>';
    xmlSTR = xmlSTR.toString().replace(/(^"|"$)/g, '');
    $.ajax({
        type : "POST",
        dataType : "xml",
        url : "https://postDataToThisURL.do",
        data : "xmlSTR",
        contentType : "text/xml",
        cache : false,
        processData : false,
        success: function (data) {
            if (data) {
            url = $(data).find("URL").text();
            console.log(data)
            console.log(url)
            window.open(url, "popupWindow", "width=1000,height=600,scrollbars=yes");              
            }
         else {
            // do something
         }
        }
    });
    e.preventDefault();
});

【问题讨论】:

  • 在显示的代码中,您的xmlSTR XML 字符串确实以引号字符开头,它以&lt; 开头并以&gt; 结尾。你不能删除一开始就不存在的东西。
  • @nnnnnn 它以单引号开头?那是问题吗?当我将其更改为常规双引号 " 时,我开始收到 Uncaught SyntaxError: Unexpected number 错误。
  • 那个单引号字符不是字符串的一部分,它是 JS 字符串文字语法的一部分。该行创建了一个字符串,其中包含外部单引号之间的所有字符,不包括那些引号字符本身。因此,例如,var x = 'abc'x 设置为三个字符的字符串 abc
  • 如果您真的想添加引号,可以查看以下链接:通过转义它们或使用单引号和双引号的组合stackoverflow.com/questions/242813/…

标签: javascript jquery ajax xml cxml


【解决方案1】:

去掉这行的引号:

data : "xmlSTR",

...实现它:

data : xmlSTR,

按照您的方式,您将 data 值设置为文字字符串 "xmlSTR",即字符 x、m、l、S、T、R。您想将其设置为 变量 xmlSTR.

【讨论】:

  • 就是这样。我不知道我怎么会错过这么久。无论我使用什么语言,字符串都是字符串。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多