0

I want to be more restrictive with my split by only take the string that is given. I mean it should replace only the string that is given, not the one with _dyna.

I don't know how to convert my split to resolve that.

My wish is respect caps and only if the string is the same as the given one

I think it's only possible to respect caps but maybe someone here know how to do all I want to do

var base = "depends_on: - tomato-app - guacamole_dyna - GUACAMOLE - guacamole - guAcamole"

var newStr = base.split("guacamole").join("newstring");

console.log(newStr)
Jerome
  • 1,162
  • 2
  • 16
  • 32

1 Answers1

1

You could use a regular expression which uses whitespace or stast or end of the string. Then replace only the second match.

var base = "depends_on: - tomato-app - guacamole_dyna - GUACAMOLE - guacamole - guAcamole",
    search = 'guacamole',
    replace = 'newstring',
    regex = new RegExp('(^|\\s)' + search + '(?=\\s|$)', 'g'),
    newStr = base.replace(regex, '$1' + replace);
    
console.log(newStr);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • can I put a variable instead of typing `guacamole` ? Because I tried like this : `replace('/(^|\s)' + myVar + '(?=\s|$)/g', "$1newstring");` but it doesn't work – Jerome May 30 '17 at 11:11
  • 1
    @Jerome, yes, you can build a new regular expression out of a string with the constructor of `RegExp`. – Nina Scholz May 30 '17 at 11:17
  • 1
    It works like a charm ! Thank you so much for the nice input (and it's not the first time that you help me with a great input) – Jerome May 30 '17 at 11:31