javascript - 如何在 Javascript 中选择两个字符之间的文本?

标签 javascript jquery html

所以我目前正在尝试找出如何在两个字符之间选择文本(例如我将使用斜杠/)

这是我到目前为止所拥有的。

<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    function startWhenLoaded() {
      var text = $("p").text();
      var secondStartingPoint, startPointOne, startPointTwo;
      if (text.indexOf("/", 0) !== -1) {
        //I did -1 because indexOf returns -1 if nothing is found.
        /*Also, the second argument in indexOf() acts as my starting 
        point for searching.*/
        secondStartingPoint = text.indexOf("/") + 1;
        startPointOne = text.indexOf("/") + 1;
        if (text.indexOf("/", secondStartingPoint) !== -1) {
          startPointTwo = text.indexOf("", secondStartingPoint) + 1;
          var selectedText = slice(startPointOne, startPointTwo);
          $("body").append("<p>" + selectedText + "</p>");
          //but nothing happens.
        }
      }
  </script>
</head>

<body onload="startWhenLoaded()">
  <p>/can I select and duplicate this?/</p>
</body>

</html>

但它没有做任何事情。

最佳答案

可以简单地通过使用正则表达式来实现,例如:

<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    function startWhenLoaded() {
      var text = $("p").text();
      var extracted = text.match(/\/(.*)\//).pop();

      alert('The extracted text is :'+extracted);
    }
  </script>
</head>

<body onload="startWhenLoaded()">
  <p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>

</html>

关于javascript - 如何在 Javascript 中选择两个字符之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53521932/

相关文章:

javascript - 从背景颜色列表中选择并为每个元素应用不同的颜色

javascript - 点击填写表格?

Javascript DOM 将图像数组加载到 div 背景中?

javascript - JS 和 JSON - 如何查找位置数

javascript - 在可拖动的 div 中闪烁

javascript - 点击提交表单

javascript - 使用 Three.js 获取两个 3d 向量之间的方向?

javascript - 删除索引后的所有项目

javascript - 动画添加边框(增长然后收缩)

python - scrapy获取不完整的html