<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>输入名字和链接转换成对象</title>
</head>
<style>
</style>
<body>
<input type="text" id="nameInput" placeholder="名字+空格+链接输入示范:可莉 https://">
<button onclick="convertName()">转换</button>
<p id="result">名字+空格+链接输入示范:可莉
https://i2.wp.com/genshinbuilds.aipurrjects.com/genshin/characters/klee/image.png?strip=all&quality=100&w=140
转换成:{
star: "45",
name: "可莉",
image:
"https://i2.wp.com/genshinbuilds.aipurrjects.com/genshin/characters/klee/image.png?strip=all&quality=100&w=140"
},</p>
<script>
function parseInput(input) {
// 去除字符串两端的空格,并替换中间的多余空格为一个空格
input = input.trim().replace(/\s+/g, ' ');
// 将输入字符串按空格分割
const parts = input.split(' ');
if (parts.length !== 2) {
throw new Error('输入格式不正确');
}
// 提取名称和图片URL
const name = parts[0].trim();
const image = parts[1].trim();
// 验证URL是否有效
if (!isValidUrl(image)) {
throw new Error('无效的图片URL');
}
// 构建输出对象
const output = {
star: "45", // 修改这里,将数字4改为字符串"4"
name: name,
image: image
};
// 将对象转换为字符串,并去掉属性名的双引号,保留属性值的双引号
let result = JSON.stringify(output, null, 2)
.replace(/"(\w+)":\s*/g, '$1: ')
.replace(/:\s*"/g, ': "');
return result;
}
function isValidUrl(url) {
const urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
return urlPattern.test(url);
}
function convertName() {
const inputValue = document.getElementById('nameInput').value;
try {
const result = parseInput(inputValue);
document.getElementById('result').innerText = result;
} catch (error) {
alert(error.message);
}
}
// 示例输入
const input = "安柏 https://i2.wp.com/genshinbuilds.aipurrjects.com/genshin/characters/amber/image.png?strip=all&quality=100&w=140";
console.log(parseInput(input));
</script>
</body>
</html>