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

时间:2018-11-28 14:39:32

标签: javascript jquery html5

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

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

<!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>

但是它什么也没做。

2 个答案:

答案 0 :(得分:2)

只需使用正则表达式即可实现:

<!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>

答案 1 :(得分:0)

正则表达式是获得解决方案的最简单,最简单的方法。 使用exec()函数在'/'之间获取文本;

console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))