WebCoder
WebCoder

Reputation: 45

How do I select text between two characters in Javascript?

So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )

Here is what I have so far.

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

But it doesn't do anything.

Upvotes: 2

Views: 221

Answers (2)

Ajit Kumar
Ajit Kumar

Reputation: 1505

Regex is simplest and easiest way to get your solution. use exec() function to get text between '/';

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

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

It could be achieved simply by using a regex like :

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

Upvotes: 2

Related Questions