Home > Software design >  Get two words before and after a specific word in JavaScript regex
Get two words before and after a specific word in JavaScript regex

Time:04-11

I have some lines like

go-usa-to-canada. Now I want find words before and after -to-.

Example:

go-usa-to-canada => usa,canada
go-location-a-to-b-location => a,b
word-for-test-to-final-word => test,final

I was using /((?: |^)\w ){1}-to-(\w (?: |$)){1}/. But it's not working when I have multiple words before and after -to-

CodePudding user response:

You can match

(?<=-)(\w )-to-(\w )

The word preceding "-to-" is saved to capture group 1; the word following "-to-" is saved to capture group 2.

Demo

The regular expression has the following elements.

(?<=-)  # positive lookahead asserts next character matched is preceded
        # by a hyphen
(\w )   # match word preceding '-to-', save to capture group 1
-to-    # match '-to-'
(\w )   # match word following '-to-', save to capture group 2

CodePudding user response:

Rather Than Regex I Felt Its Easier To Use .split() function.

function extract(txt){
    for (i=0;i<txt.split("-").length;i  ){
        if (txt.split("-")[i] == "to"){
            return txt.split("-")[i-1]   ","   txt.split("-")[i 1]
        }
    }
}
        

Explaining: Its First Splitting The String Based on the - then its looping through the array to find the element having towritten. Then It Returns the previous and next element of that same array.

console.log(extract("go-usa-to-canada"))
// Returns usa,canada

CodePudding user response:

Try regex => /.*?(\w )\W to\W (\w )/gm

Sample code:

const regex = /.*?(\w )\W to\W (\w )/gm;

// Alternative syntax using RegExp constructor
// const regex = new RegExp('.*?(\\w )\\W to\\W (\\w )', 'gm')

const str = `go-usa-to-canada
go-location-a-to-b-location
word-for-test-to-final-word`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex  ;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
    console.log("\n\n")
}
  • Related