1

I'm taking this post as reference where they suggest this solution:

Current

Str = 'MyLongString:StringIWant;'

Desired Output

newStr = 'StringIWant'

Solution

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

but what if i have multiple incidence? in my case i have a long text, lets say:

str = 'MyLongString has :multiple; words that i :need; to :extract;'

New desired output:

strarray = ["multiple","need","extract"]

When i apply the suggested solution its just getting the last word "extract"

2 Answers2

0

This is one way of doing it, running a loop from start of the string to the end and using indexOf and substring to get the desired result

const str = 'MyLongString has :multiple; words that i :need; to :extract;';

function extractWords(str) {
    const words = [];
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) === ':') {
            const stopIndex = str.indexOf(';', i);
            if (stopIndex !== -1)
                words.push(str.substring(i + 1, stopIndex));
        }
    }
    return words;
}

console.log(extractWords(str));
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0

The linked suggestion is actually using a string function instead of a regular pattern; a simple pattern like /:\w+;/g gives us all desired words, thanks to the /g flag.

We can get rid of the pre- and postfix using lookarounds, however, those may not work in all JavaScript environments (but actually it is less of a problem now since all major browsers support the lookbehind (?<=..) operator in their latest versions, and the lookahead (?=..) is supported since forever).

str = 'MyLongString has :multiple; words that i :need; to :extract;'
let result = str.match(/:\w+;/g) || [];
console.log(result);

let result2 = str.match(/(?<=:)\w+(?=;)/g) || [];
console.log(result2);
wp78de
  • 18,207
  • 7
  • 43
  • 71