Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve substring between two characters

I have string like this

  var str = "#it
              itA
              itB
              _
             #et
              etA
              etB
             _
             etC
             etD"

How can I retrieve elements between # and _. As of now I am splitting the text with new line but unable to workout this. Please help me on this. Please use this fiddle http://jsfiddle.net/h728C/2/

like image 979
Exception Avatar asked Dec 06 '22 16:12

Exception


2 Answers

IF you simply want the FIRST string BETWEEN you can use:

var mys= str.substring(str.indexOf('#')+1,str.indexOf("_"));

this returns: "it itA itB"

like image 163
Mark Schultheiss Avatar answered Dec 20 '22 13:12

Mark Schultheiss


I've posted some solution in fidde. It uses the Regex

var str = $('#a').text();
var pattern = /#([\s\S]*?)(?=_)/g;
var result = str.match(pattern);
for (var i = 0; i < result.length; i++) {
    if (result[i].length > 1) {
       result[i] = result[i].substring(1, result[i].length);
    }
    alert(result[i]);
}

Strip the end and beginning.

Edit

I've updated the fiddle and the code. Now it strips the beginning # and ending _. You can use either. Whichever is convenient. ​ ​

like image 39
Oybek Avatar answered Dec 20 '22 13:12

Oybek