本文主要是介绍输入名字和链接转换成对象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<!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('输入格式不正确');}// 提取名称和图片URLconst 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>
这篇关于输入名字和链接转换成对象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!