首页 > 解决方案 > 在 sweetalert JavaScript 中格式化字符串

问题描述

我有返回此字符串的 API:

string.Format(
  "Something went wrong with {0}." +
    "<br>" +
    " Do you want to continue with?" +
    "<strong>" +
    "{1}" +
    "</strong>",
);

我想把它传递给 SweetAlert2。但这是结果:

在此处输入图像描述

我也尝试了\r\n\n但什么也没发生。

这是我的 JavaScript:

var mess = "@messaggio";
Swal.fire({
  heightAuto: false,
  title: "Richiesta Disconnessione",
  html: mess,
  icon: "warning",
  showCancelButton: true,
  confirmButtonColor: "#3085d6",
  cancelButtonColor: "#d33",
  confirmButtonText: "Yes",
  cancelButtonText: "No",
});

我想把第二个短语放在第一个词下面,最后一个词应该是粗体。

任何建议如何解决这个问题?

提前致谢!

标签: javascriptsweetalertsweetalert2

解决方案


您使用的是旧版本的 sweetalert

查看更多信息:https ://sweetalert.js.org/docs/

// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

var mess = "Something went wrong with {0}.\nDo you want to continue with {1}?".format("Macchina", "carrello"); 
swal(mess,{
  heightAuto: false,
  title: 'Richiesta Disconnessione',
  icon: 'warning',
  buttons: {
  cancel: {
    text: "No",
    value: null,
    visible: true,
    className: "sweet-cancel",
    closeModal: true,
  },
  confirm: {
    text: "Yes",
    value: true,
    visible: true,
    className: "sweet-confirm",
    closeModal: true
  }
}
})
.sweet-confirm { color: #3085d6; }
.sweet-cancel { color: #d33; }
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>


推荐阅读