Javascript从短代码字符串中提取属性

时间:2016-06-01 19:05:06

标签: javascript regex wordpress

我有一个Javascript应用程序,可以从WordPress数据库中检索短代码。所以我最终可能得到一个像这样的变量:

var shortcode = '[wp-form id="1946" title="My Test Form"]';

我希望使用纯Javascript来访问属性,以便我可以提取标题等。我想这将是一些形式或正则表达式和split()。但到目前为止,我的努力因空白分裂而受挫。

任何想法都非常感激。

4 个答案:

答案 0 :(得分:3)

尝试使用此代码:

var shortcode = '[wp-form id="1946" title="My Test Form"]';    
var attributes = {};
shortcode.match(/[\w-]+=".+?"/g).forEach(function(attribute) {
    attribute = attribute.match(/([\w-]+)="(.+?)"/);
    attributes[attribute[1]] = attribute[2];
});
console.log(attributes);

输出:

Object {id: "1946", title: "My Test Form"}

答案 1 :(得分:1)

在这种情况下,请勿尝试使用String.prototype.split,使用其值描述属性并使用RegExp.prototype.exec构建模式以匹配它们:

var re = /([\w-]+)="([^"]*)"/g; 
var str = '[wp-form id="1946" title="My Test Form"]';
var m;

while ((m = re.exec(str)) !== null) {
    console.log(m[1] + "\n" + m[2] + "\n");
}

答案 2 :(得分:1)

好吧,即使我迟到了,我也会回答。我很惊讶没有人抱怨"you can't parse with just a regular expression!"我想这曾经是一个更时髦的评论。无论如何,我认为仅使用正则表达式并看到已经给出的一些合理尝试是完全合理的。

但是,如果你想真的解析标签,这里是一个快速解析器我掀起了。

function parseShortCode(shortCode) {
  var re = /(\s+|\W)|(\w+)/g;
  var match;
  var token;
  var curAttribute = '';
  var quoteChar;
  var mode = 'NOT STARTED'
  var parsedValue = {
    name: '',
    attributes: {}
  };
  
  while ((match = re.exec(shortCode)) != null) {
    token = match[0];
    switch (mode) {
      case 'NOT STARTED':
        if (token == '[') {
          mode = 'GETNAME';
        }
        break;
      case 'GETNAME':
        if (!(/\s/.test(token))) {
          parsedValue.name += token;
        } else if (parsedValue.name) {
          mode = 'PARSING';
        }
        break;
      case 'PARSING':
        // if non text char throw it
        if (token == "]") { mode = 'COMPLETE'; }
        else if (token == "=") {
          if (!curAttribute) throw ('invalid token: "' + token + '" encountered at ' + match.index);
          else mode = 'GET ATTRIBUTE VALUE';
        }
        else if (!/\s/.test(token)) {
          curAttribute += token;
        } else if (curAttribute) {
          mode = 'SET ATTRIBUTE'
        }
        break;
      case 'SET ATTRIBUTE':
        // these are always from match[1]
        if (/\s/.test(token)) { parsedValue.attributes[curAttribute] = null; }
        else if (token == '=') { mode = 'GET ATTRIBUTE VALUE'; }
        else { throw ('invalid token: "' + token + '" encountered at ' + match.index); }
        break;
      case 'GET ATTRIBUTE VALUE':
        if (!(/\s/.test(token))) {
          if (/["']/.test(token)) {
            quoteChar = token;
            parsedValue.attributes[curAttribute] = '';
            mode = 'GET QUOTED ATTRIBUTE VALUE';
          } else {
            parsedValue.attributes[curAttribute] = token;
            curAttribute = '';
            mode = 'PARSING';
          }
        }
        break;
      case 'GET QUOTED ATTRIBUTE VALUE':
        if (/\\/.test(token)) { mode = 'ESCAPE VALUE'; }
        else if (token == quoteChar) {
          mode = 'PARSING';
          curAttribute = '';
        }
        else { parsedValue.attributes[curAttribute] += token; }
        break;
      case 'ESCAPE VALUE':
        if (/\\'"/.test(token)) { parsedValue.attributes[curAttribute] += token; }
        else { parsedValue.attributes[curAttribute] += '\\' + token; }
        mode = 'GET QUOTED ATTRIBUTE VALUE';
        break;

    }
  }
  if (curAttribute && !parsedValue.attributes[curAttribute]) {
  	parsedValue.attributes[curAttribute] = '';
  }
  return parsedValue;
}

function doUpdate() {
  var text = document.getElementById('shortcode').value;
  var output;
  try {
    output = parseShortCode(text);
  } catch (err) {
    output = err;
  }

  document.getElementById('result').innerHTML = JSON.stringify(output);
}

document.getElementById('updateBtn').addEventListener("click", doUpdate);
doUpdate();
Short Code:
<textarea type=text id="shortcode" style="width:100%; height:60px">[wp-form id="1946" title="My Test Form"]</textarea>
<div>
  <button id="updateBtn">Update</button>
</div>
<div>
  <pre id="result"></pre>
</div>

我确定这有错误,但我让它与你的案子一起工作,有些情况下其他答案无法处理。除非短代码变得非常强烈,否则我只会坚持使用正则表达式。但如果您遇到不带引号的属性值和空属性等内容,这可能对您有用。

答案 3 :(得分:0)

可以使用正则表达式完成

var shortcode = '[wp-form id="1946" title="My Test Form"]';
// use of regex to extract id , title 
var arr  = /id\=\"(.*?)\".*title=\"(.*?)\"/.exec(shortcode);
var id = arr[1];
var title = arr[2];
相关问题