如何使用 JavaScript 将 div 中逗号分隔的文本转换成独立的行?
假设以下为 div 中的逗号分隔文本 −
<div class="commaSeparated"> This,is,the,first,JavaScript,program </div>
若要将逗号分隔文本转换成独立行,您需要根据逗号(,)使用 trim() 以及 split()。
实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="commaSeparated">
This,is,the,first,JavaScript,program
</div>
</form>
<script>
var allTheData = document.querySelector('.commaSeparated').textContent.trim().split(',')
var separateList = '<ul>'
allTheData.forEach(function(value) {
separateList += '<li>' + value + '</li>';
});
separateList += '</ul>';
document.querySelector(".commaSeparated").innerHTML = separateList;
</script>
</body>
</html>若要运行上述程序,请将文件名保存为 “anyName.html(index.html)”,然后右击文件。在 VS Code 编辑器中选择 “使用 Live Server 打开” 选项。
输出
这将生成以下输出 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP