首页 > 解决方案 > Multiple String Manipulation using js

问题描述

I have a text area that I will paste some data in for example like so

01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019

And when I click submit all the text inside the text box to give an output below something like this

06/01/2019 <!-- dd/mm/yyyy -->
07/01/2019
08/01/2019
08/01/2019
10/01/2019

I have managed to this on python using this code

filepath = ('date.txt')
f = open("newdate.txt", "w+")
new = []
with open(filepath) as fp:
    for line in fp:
        line = line.strip('\n')
        new = line.split("-")
        f.write(new[1] + "/" + new[2] + "/" + new[0] + "\n")
        print(new[1] + "/" + new[2] + "/" + new[0] + "\n")
f.close()

I am new to JavaScript and jQuery so wondering how can i achieve that in jQuery

标签: javascriptjqueryhtml

解决方案


您可以在表单上注册一个onsubmit侦听器,然后在处理程序中执行解析文本区域值的逻辑。

以下代码段是如何执行此操作的示例:

// Register 'submit' event listener
document.querySelector('#form')
  .addEventListener('submit', e => {
    // Prevent default action so that page doesn't refresh
    e.preventDefault();

    // Get the text from the textarea
    let text = document.querySelector('#text').value;

    // Split the lines
    let converted = text.split('\n')
      // Convert each line
      .map(str => {
        // Extract the date parts
        let [mm, dd, yyyy] = str.split('-');
        
        // Return the desired format by joining the date parts with /
        return [dd, mm, yyyy].join('/');
      });

    // Print result to console
    console.log(converted);
  });
<form id="form">
  <textarea id="text"></textarea>
  <button type="submit">submit</button>
</form>


推荐阅读