javascript - 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
解决方案
您可以在表单上注册一个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>
推荐阅读
- java - 根据特定的单元格值划分excel表
- r - 在 R 中显示密度图(ggplot2)的 x 轴上的显式点
- css - 如何在不使用 React Native 中的字符串的情况下将宽度(100%)设置为与其父级相同?
- c# - WPF 窗口内托管本机 HWND 控件的 DPI 缩放问题
- swift - 当测试包含 HTTP 请求时,Quickspec 测试永远不会成功执行
- android - Gradle 文件推送到 github 仓库
- javascript - 从 Discord Bot 播放 Youtube 视频
- asp.net-mvc - 将“详细信息”视图显示为模式弹出窗口
- python - 查找仅在某些列中具有值的行
- r - 误差优化 birnbaum sanders 分布 fnpar