0

I want to format a date time like this:

yyyy-MM-dd hh:mm:ss

if I return a string is like this:

2016-07-02 20:14:12

some code is like this(all code is here):

let token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|'[^']*'|'[^']*'/g;
mask.replace(token, (match) => {
      if (match in flags) {
        return flags[match];
      }
      return match.slice(1, match.length - 1);
    });

The problem is now I want the number is wrapped by React.Component, such as:

<span>2016</span>-<span>07</span>-<span>02</span> <span>20</span>:<span>14</span>:<span>12</span>

I want to point out that the wrapped element is not always span, maybe a component defined by myself, such as MyComponent

2

2 Answers 2

2

You can try something like this:

Note: this is plain string computation. You can check the logic and update for JSX.

var str = "2016-07-02 20:14:12";
var result = str.split(" ").map(function(a){
  var delimeter = a.match(/[^0-9]/)[0];
  return a.split(delimeter).map(function(item){
    return "<span>" + item + "<span>";
  }).join(delimeter);
}).join(" ");

document.getElementById("result").innerText = result;
<span id="result"></span>

For JSX I guess you can try something like this:

var str = "2016-07-02 20:14:12";
var result = str.split(" ").map(function(a){
  var delimeter = a.match(/[^0-9]/)[0];
  return a.split(delimeter).map(function(item){
    return <span>{item}<span>;
  }).join(delimeter);
}).join(" ");
Sign up to request clarification or add additional context in comments.

Comments

0

After some research I found that existing libraries doesn't fit my requirements. So, of course, I have written my own:

https://github.com/EfogDev/react-process-string

It is very easy to use. Your case example:

let result = processString({
    regex: /[0-9+]/gim,
    fn: (key, match) => <span key={key}>{match[1]}</span>
})(mask);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.