Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Substring between two characters using javascript

People also ask

How do I find a string between two characters?

To get a substring between two characters:Get the index after the first occurrence of the character. Get the index of the last occurrence of the character. Use the String. slice() method to get a substring between the 2 characters.

How do you use substring in JavaScript?

The substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string.

How do you find a specific character in a string JavaScript?

JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.


You can try this

var mySubString = str.substring(
    str.indexOf(":") + 1, 
    str.lastIndexOf(";")
);

You can also try this:

var str = 'one:two;three';    
str.split(':').pop().split(';')[0]; // returns 'two'

Use split()

var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);

arrStr will contain all the string delimited by : or ;
So access every string through for-loop

for(var i=0; i<arrStr.length; i++)
    alert(arrStr[i]);

@Babasaheb Gosavi Answer is perfect if you have one occurrence of the substrings (":" and ";"). but once you have multiple occurrences, it might get little bit tricky.


The best solution I have came up with to work on multiple projects is using four methods inside an object.

  • First method: is to actually get a substring from between two strings (however it will find only one result).
  • Second method: will remove the (would-be) most recently found result with the substrings after and before it.
  • Third method: will do the above two methods recursively on a string.
  • Fourth method: will apply the third method and return the result.

Code

So enough talking, let's see the code:

var getFromBetween = {
    results:[],
    string:"",
    getFromBetween:function (sub1,sub2) {
        if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
        var SP = this.string.indexOf(sub1)+sub1.length;
        var string1 = this.string.substr(0,SP);
        var string2 = this.string.substr(SP);
        var TP = string1.length + string2.indexOf(sub2);
        return this.string.substring(SP,TP);
    },
    removeFromBetween:function (sub1,sub2) {
        if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
        var removal = sub1+this.getFromBetween(sub1,sub2)+sub2;
        this.string = this.string.replace(removal,"");
    },
    getAllResults:function (sub1,sub2) {
        // first check to see if we do have both substrings
        if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return;

        // find one result
        var result = this.getFromBetween(sub1,sub2);
        // push it to the results array
        this.results.push(result);
        // remove the most recently found one from the string
        this.removeFromBetween(sub1,sub2);

        // if there's more substrings
        if(this.string.indexOf(sub1) > -1 && this.string.indexOf(sub2) > -1) {
            this.getAllResults(sub1,sub2);
        }
        else return;
    },
    get:function (string,sub1,sub2) {
        this.results = [];
        this.string = string;
        this.getAllResults(sub1,sub2);
        return this.results;
    }
};

How to use?

Example:

var str = 'this is the haystack {{{0}}} {{{1}}} {{{2}}} {{{3}}} {{{4}}} some text {{{5}}} end of haystack';
var result = getFromBetween.get(str,"{{{","}}}");
console.log(result);
// returns: [0,1,2,3,4,5]

var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant

I like this method:

var str = 'MyLongString:StringIWant;';
var tmpStr  = str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'

You can use a higher order function to return a 'compiled' version of your extractor, that way it's faster.

With regexes, and compiling the regex once in a closure, Javascript's match will return all matches.

This leaves us with only having to remove what we used as our markers (ie: {{) and we can use string length for this with slice.

function extract([beg, end]) {
    const matcher = new RegExp(`${beg}(.*?)${end}`,'gm');
    const normalise = (str) => str.slice(beg.length,end.length*-1);
    return function(str) {
        return str.match(matcher).map(normalise);
    }
}

Compile once and use multiple times...

const stringExtractor = extract(['{','}']);
const stuffIneed = stringExtractor('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]

Or single-time use...

const stuffIneed = extract(['{','}'])('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]

Also look at Javascript's replace function but using a function for the replacement argument (You would do that if for example you were doing a mini template engine (string interpolation) ... lodash.get could also be helpful then to get the values you want to replace with ? ...

My answer is too long but it might help someone!