Piyush
Piyush

Reputation: 63

Selecting part of a string

I have a jquery string, say x.

x = '##_##Donec commodo imperdiet diam##_###, eget porttitor nisi blandit facilisis. Morbi vitae lectus id nunc ultricies tincidunt.';

I want to select the part of string between the ##_## and ##_### i.e. "Donec commodo imperdiet diam" from the above example.

Thanks in advance.

Upvotes: 0

Views: 92

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

This is the more generic code how to get a text between 2 different (but constant) delimiters in JS:

teststr = '##_##Donec commodo imperdiet diam##_###, eget porttitor nisi blandit facilisis. Morbi vitae lectus id nunc ultricies tincidunt.##_##More text##_### here.';
function GetSubstrs(istr) {
  var res = [];
  var start_pos = istr.indexOf('##_##');
  while (start_pos > -1)
  {
    var end_pos = istr.indexOf('##_###',start_pos + 5);
    var text_to_get = istr.substring(start_pos + 5,end_pos)
    res.push(text_to_get);
    start_pos = istr.indexOf('##_##', end_pos + 6);
  }
  return res;
}

alert(GetSubstrs(teststr));

Upvotes: 1

Powkachu
Powkachu

Reputation: 2268

I think you can do:

var res = str.split('##_##')[1].split('##_###')[0];

Upvotes: 3

Abhishekh Gupta
Abhishekh Gupta

Reputation: 6236

You can try this:

var myString = "##_##Donec commodo imperdiet diam##_###, eget porttitor nisi blandit facilisis. Morbi vitae lectus id nunc ultricies tincidunt.";
var myRegexp = /##_##([^#]*)##_###/g;
var match = myRegexp.exec(myString);
console.log(match[1]);

Upvotes: 1

Related Questions