javascript - 如何分割输入标签HTML的字符串?

标签 javascript html

当用户在输入标记中输入以下链接时,我只需要字符串的最后一部分,以尽量减少输入错误 - 两个输入字段生成一个用户可以复制和使用的新链接。

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" />
 

最佳答案

这是一个 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
}

在您的代码中,您可以使用这两个函数来检查和解析 lNamefName,如下所示:

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"/>

关于javascript - 如何分割输入标签HTML的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55463375/

相关文章:

html - 空的 div 不会增长

javascript - 更改 css 样式并使用 jQuery 附加文本

html - 如何限制页脚的宽度

javascript - 在 Javascript 中强制使用十进制值,即使是整数

javascript - 如何在点击喜欢和刷新页面时保持按钮的颜色

javascript - 如何使用 Node.js 处理 CSS?

html - 如何让标题和两个按钮与边框正确对齐?

javascript - 悬停时一个接一个地显示子菜单

javascript - 在 AngularJs 的 UI.Bootstrap tab-heading 指令中使用 X-editable

javascript - 如果调用函数时提供的参数包含空格,则不会调用函数