Home > Net >  Javascript get single word before a specific string
Javascript get single word before a specific string

Time:08-03

I have two strings like below.

(1-50 of 128 search records) (128 search records in total)

I need to extract only the word 128 which is just a previous word of "search". Can anyone guide me how to extract it in javascript?

CodePudding user response:

You can use lookahead (?="the text after here") to get the number which before a white space and "search" word

const getResultNumber = (str) => {
  return str.match(/\d (?=\ssearch)/)[0]
}

console.log(getResultNumber("1-50 of 128 search records"))
console.log(getResultNumber("150 search records in total"))

CodePudding user response:

Here's the classic indexOf() variant with slice().

const str = "(1-50 of 128 search records)";

const inBetween = ["of", "search"];
const result =  str
  .slice(
    str.indexOf(inBetween[0])   inBetween[0].length,
    str.indexOf(inBetween[1])
  )
  .trim();
console.log(result);

CodePudding user response:

You could use something like this.

let string = '(1-50 of 128 search records)';
let arr = string.match(/\w /g); // ["1", "50", "of", "128", "search", "records"]
console.log(arr[3]);

  • Related