分割字符串的最佳方法?

时间:2019-12-30 14:08:09

标签: javascript reactjs

我正在尝试解析字符串数组,例如

Captain America
004

我要如何渲染(反应)

条款

    1. 条款和条件标题(末尾加点)。此处提供一些常规信息。
      • 5.1。小节标题。一些更多信息。
    1. 条款和条件标题现在以半列结尾:一些常规信息。
      • 6.1。小节标题。一些更多信息。

到目前为止,我所做的是: (忽略切片fn)

const example = [
'Terms and Conditions',
'5. Terms and Conditions Title (dot at the end). Some general info here.',
'5.1. Sub-section title. Some more info here.',
'6. Terms and Conditions Title ends with semi-column now: Some general info here.',
'6.1. Sub-section title. Some more info here.',
];

);

但是,我需要一种更好的方法来确定是否应拆分文本(粗体和普通),以及拆分的更好方法。

问题:我的代码当前不_.split以'。'结尾的文本或':',相反,我剩下的整个字符串

return (
<div>
  {_.slice(_.map(example, (item, index) => {
    const key = index;
    if (index === 0) { // First text
      return (<h1 key={key}>{item}</h1>);
    }
    if (item === '') {
      return (<br key={key} />);
    }
    if ((/^(\d|\d\d)\. /).test(item)) { // "5. Heading"
      const list = _.split(item, / \.|:/, 2);
      const bold = _.size(list) === 2 ? list[0] : item;
      const normal = _.size(list) === 2 ? list[1] : '';
      return [
        <span className="bold" key={`bold-${key}`}>{bold}</span>,
        <p className="normal"  key={`normal-${key}`}>{normal}</p>,
      ];
    }
    return (<p className="normal" key={key}>{item}</p>);
  }), startIndex, !_.isNil(endIndex) ? endIndex : _.size(example))}
</div>

所以问题就在这里(lodash函数):

'5. Terms and Conditions Title (dot at the end). Some general info here.' <- BOLD.

2 个答案:

答案 0 :(得分:1)

您可以将此平坦数组转换为嵌套数组,然后,可以很容易地迭代每个深度并呈现适当的布局。

const example = [
  'Terms and Conditions',
  '5. Terms and Conditions Title (dot at the end). Some general info here.',
  '5.1. Sub-section title. Some more info here.',
  '5.2. Sub-section title. Some more info here.',
  '6. Terms and Conditions Title ends with semi-column now: Some general info here.',
  '6.1. Sub-section title. Some more info here.',
];

function getChildrenAtDepth(depth, nestedObj) {
  let current = nestedObj[nestedObj.length - 1].children;

  for (i = 0; i < depth - 1; i++) {
    current = current[current.length - 1].children;
  }

  return current

}

const nestedData = example.reduce((result, currentLine) => {
  const matches = currentLine.match(/^(\d+\.?)+\s/);

  if (matches) {
    const depth = matches[0].split('.').length - 1;

    const children = getChildrenAtDepth(depth, result);
    children.push({
      title: currentLine,
      children: []
    })
  } else {
    result.push({
      title: currentLine,
      children: []
    })

  }

  return result;
}, []);


var Comp = function Comp(_ref) {
  var data = _ref.data;
  var depth = _ref.depth;
  return React.createElement("ul", {
    className: 'depth-' + depth
  }, data.map(function(header) {
    return React.createElement("li", null, header.title, header.children.length > 0 && React.createElement(Comp, {
      data: header.children,
      depth: depth + 1
    }));
  }));
};

ReactDOM.render(React.createElement(Comp, {
  data: nestedData,
  depth: 0
}), document.getElementById('root'));
ul {
  padding: 0;
  margin: 1em 0;
  list-style: none;
}

ul.depth-0>li {
  font-size: 1.44rem;
  font-weight: 600;
}

ul.depth-1>li {
  font-size: 1.2rem;
}

ul.depth-2>li {
  font-size: 1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

此代码段将生成

[{
  title: 'Terms and Conditions',
  children: [{
    title: '5. Terms and Conditions Title (dot at the end). Some general info here.',
    children: [{
      title: '5.1. Sub-section title. Some more info here.',
      children: []
    }, {
      title: '5.2. Sub-section title. Some more info here.',
      children: []
    }]
  }, {
    title: '6. Terms and Conditions Title ends with semi-column now: Some general info here.',
    children: [{
      title: '6.1. Sub-section title. Some more info here.',
      children: []
    }]
  }]
}]

答案 1 :(得分:0)

好的,我已经解决了。花了我一些时间。

执行此工作的正确正则表达式基本上是:

5。标题。其他内容

spreadsheet_id = 'your-spreadSheet-id'
ranges = "A1:A" # It will get the indo until the last row with data
value_render_option = "DIMENSION_UNSPECIFIED"
value_input_option = "USER_ENTERED"

# Body for the request 
value_range_body = {
        "values": [
            [
                "A11",
                "B11"
            ],
            [
                "A12",
                "B12"
            ]
        ],
        "majorDimension": "DIMENSION_UNSPECIFIED"
}

 request = service.spreadsheets().values()\
        .append(spreadsheetId=spreadsheet_id, range=ranges, valueInputOption=value_input_option, body=value_range_body)

request.execute()

如果我想将其拆分为3个字符串

  1. 标题。其他内容

    ([['5。,,'Title','Other stuff'])

正则表达式可能是

/^[\d|\d\d]\.\s[A-Z].*?[.!?:]/

但是由于lodash拆分的工作原理,我不得不提出另一种解决方案:

/^(\d|\d\d)\.\s[A-Z].*?[.!?:]/