正则表达式将html标记替换为特殊字符内的所有属性

时间:2017-08-08 19:36:49

标签: javascript regex

我的正则表达技能不是很高,所以如果我的问题会打扰某人,我会提前道歉。

我试图以两种方式转换字符串

  1. 来自特殊字符=>带属性的html标记
  2. 使用attributes =>格式化html标记特殊字符
  3. 第一种方式正常工作,下一步:

    var string = "User template user info: {{userFirstname}} - {{userLastname}}";
    var text = string
                .replace(/\{{/g, "<span class='label label-danger' contenteditable='false' style='padding: 6px; color: #FFFFFF; font-size: 16px;'>")
                .replace(/\}}/g, "<span contenteditable='false' class='remove-tag fa fa-times'></span></span>&nbsp;");
    
    第二种方式不起作用,我无法理解原因:

    var text = 'User template user info: <span class="label label-danger" contenteditable="false" style="padding: 6px; color: #FFFFFF; font-size: 16px;">userFirstname<span contenteditable="false" class="remove-tag fa fa-times"></span></span>&nbsp; - <span class="label label-danger" contenteditable="false" style="padding: 6px; color: #FFFFFF; font-size: 16px;">userLastname<span contenteditable="false" class="remove-tag fa fa-times"></span></span>&nbsp;
    var string = text
                .replace(/<span class='label label-danger' contenteditable='false' style='padding: 6px; color: #FFFFFF; font-size: 16px;'>/g, "{{")
                .replace(/<span contenteditable='false' class='remove-tag fa fa-times'><\/span><\/span>&nbsp;/g, "}}")
    

    如果有人能告诉我我失踪了什么,我感激不尽。提前致谢

3 个答案:

答案 0 :(得分:1)

虽然基于占位符的简单替换通常起作用,但使用正则表达式替换复杂的HTML元素很容易失败。

我会在这里推荐另一种方法!

最佳方法可让您控制要消除的元素和要保留的元素。底部方法剥离所有HTML并假设您知道span的内容。

var text = 'User template user info: <span class="label label-danger" contenteditable="false" style="padding: 6px; color: #FFFFFF; font-size: 16px;">userFirstname<span contenteditable="false" class="remove-tag fa fa-times"></span></span>&nbsp; - <span class="label label-danger" contenteditable="false" style="padding: 6px; color: #FFFFFF; font-size: 16px;">userLastname<span contenteditable="false" class="remove-tag fa fa-times"></span></span>&nbsp;'

function replaceSpan(text)
{
  //convert text into virtual DOM object
  var div = document.createElement("div");
  div.insertAdjacentHTML("afterbegin", text);
  //loop over children and replace
  Array.prototype.forEach.call(div.querySelectorAll("span"), function(element){
  
    if (element.contentEditable == "false" && element.classList.contains("label") && element.classList.contains("label-danger") )
    {
      elementContent = element.textContent;
      element.parentNode.replaceChild(document.createTextNode("{{"+elementContent+"}}"), element);
      
    }
  });
  console.log(div.textContent);
  return div.textContent
}

replaceSpan(text);

这也可以简化:

var text = 'User template user info: <span class="label label-danger" contenteditable="false" style="padding: 6px; color: #FFFFFF; font-size: 16px;">userFirstname<span contenteditable="false" class="remove-tag fa fa-times"></span></span>&nbsp; - <span class="label label-danger" contenteditable="false" style="padding: 6px; color: #FFFFFF; font-size: 16px;">userLastname<span contenteditable="false" class="remove-tag fa fa-times"></span></span>&nbsp;'

var string = document.createElement("div");
string.innerHTML = text;
// use textContent of div element to return text without HTML
string =  string.textContent.replace("userFirstname", "{{userFirstname}}")
          .replace("userLastname", "{{userLastname}}");
          
console.log(string);

答案 1 :(得分:0)

替换值的属性值包含在单引号class ViewController: UIViewController, UICollectionViewDataSource { // MARK: - Outlets @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout! // MARK: - view lifecycle override func viewDidLoad() { super.viewDidLoad() if #available(iOS 10.0, *) { // This causes constaint errors. // collectionViewFlowLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize // collectionViewFlowLayout.estimatedItemSize = CGSize(width: 300, height: 50) } else { // Fallback on earlier versions } } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) guard let itemCell = cell as? ItemCell else { return cell } itemCell.label.text = "blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" return cell } } 中,而contenteditable='false'属性值的属性值包含在双引号text中。这会导致由于引号不匹配而导致替换找不到指定的字符串。

contenteditable="false"变量也缺少结束text

'

答案 2 :(得分:0)

我相信这是某种解决方法,但它适用于我

 var string = text
            .replace(/<span[^>]*>/g, "{{")
            .replace(/<\/span[^>]*>/g, "")
            .replace(/{{&nbsp;/g, "}}");