当用户在输入标签中输入下面的链接时,我只想要字符串的最后一部分,以最大程度地减少输入错误-两个输入字段生成一个新的链接,用户可以复制和使用该链接。
name:id:5icOoE6VgqFKohjWWNp0Ac
(我只想要最后一个'5icOoE6VgqFKohjWWNp0Ac
'部分)
有人可以帮助我修改以下内容以实现这一目标吗?
function generateFullName() {
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + document.getElementById('fName').value + ('?context=') + document.getElementById('lName').value;
}
Enter a product ID:
<input type="text" id="fName" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' />
Enter a user ID:
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M'/><br/></p>
Tada! This would be the link for your campaign:
<input type="text" id="txtFullName" name="txtFullName" />
答案 0 :(得分:1)
这是一个JavaScript函数,该函数将字符串作为输入,并将其格式化为仅保留最后一个冒号(如果包含冒号)之后的最后一部分:
function parseColon(txt) {
return txt.split(":").slice(-1).pop();
}
例如。 parseColon("a:b:c")
将返回"c"
您可以使用以下方法验证您的输入:
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 32 && numberOfColons == 2)
return true
return false
}
在您的代码中,您可以使用以下两个函数来检查和解析lName
和fName
,如下所示:
function generateFullName() {
var lName_val = document.getElementById('lName').value;
var fName_val = document.getElementById('fName').value;
//fill in link in the output if fName and lName are valid inputs
if(isValidInput(fName_val) && isValidInput(lName_val))
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + parseColon(fName_val) + ('?context=') + parseColon(lName_val);
// otherwise, clear the output field
else
document.getElementById('txtFullName').value = "";
}
function parseColon(txt) {
// return the part after the last colon
return txt.split(":").slice(-1).pop();
}
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 38 && numberOfColons == 2)
return true
return false
}
Enter a product ID:<br>
<input type="text" id="fName" oninput="generateFullName()" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' size="50"/><br/>
Enter a user ID:<br>
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M' size="50"/><br/><br/>
Tada! This would be the link for your campaign:<br>
<input type="text" id="txtFullName" name="txtFullName" size="50"/>