2

There is a string of writing/text in a variable:

var copypaste, replaced;
var verbdb = ["keep","know","enjoy"];
var arrayLength = verbdb.length;

for (var i = 0; i < arrayLength; i++) {
    copypaste = "One of the reasons first_name keep waking up at night, is blah blah blah. Try this, let first_name know and see blah blah blah. Remember that first_name enjoy being challenged and blah blah blah.";

    replaced = copypaste.replace(RegExp("[^let]? first_name " + verbdb[i] + "(\s|\.)","g")," first_name " + verbdb[i] + "_object_s\$1");
}

What I am seeking to get from the replaced variable is to exclude ONLY when first_name is preceded by the word let.

"One of the reasons first_name keep_object_s waking up at night, is blah blah blah. Try this, let first_name know and see blah blah blah. Remember that first_name enjoy_object_s being challenged and blah blah blah.";


So in this example:

  1. the first pattern MATCHES (keep) and is replaced with _object_s added in,
  2. the second pattern does NOT match (know) because of the word "let", so no replacement
  3. the third pattern MATCHES (enjoy) and is replaced with _object_s added in.
ddarby14
  • 23
  • 2
  • It seems like you don't understand what `[]` means in regular expressions. It's not for grouping, that's what `()` is for. – Barmar Jan 17 '17 at 04:59
  • `[^let]` matches a single character that isn't `l`, `e`, or `t`, it doesn't exclude the string `let`. – Barmar Jan 17 '17 at 05:00
  • What you're looking for is a negative lookbehind, but Javascript regular expressions don't have that feature. – Barmar Jan 17 '17 at 05:01
  • See http://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent for some workarounds. – Barmar Jan 17 '17 at 05:02
  • Thanks - I will check out that link and learn more, I get the [] and () but admittedly, this code snippet had me overwhelmed and getting sloppy. – ddarby14 Jan 17 '17 at 07:13

1 Answers1

1

You can try this :

(?:\b)(?!let)(?=\w+\sfirst_name\s+(know|keep|enjoy))(\w+ \w+)\s+(\w+)

Explanation

const regex = /(?:\b)(?!let)(?=\w+\sfirst_name\s+(know|keep|enjoy))(\w+ \w+)\s+(\w+)/g;
const str = `One of the reasons first_name keep waking up at night, is blah blah blah. Try this, let first_name know and see blah blah blah. Remember that first_name enjoy being challenged and blah blah blah`;
const subst = `$2 _object_s`;

const result = str.replace(regex, subst);
console.log(result);
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
  • Wow, this is elegant and worked - bravo, I salute your mastery. i will study to learn more about what this all means. Thank you! – ddarby14 Jan 17 '17 at 07:18