0

Trying to replace everything inside brackets [ ] with an element of an array. Example:

function replacingText(){
     var names = ["Cole", "Kyle", "Chase"];
     var sentance = 'This is [Cole].'
     var regex = "\[(.*?)\]/gm";
    console.log(sentance.replace(regex, names[1])); 
}

So the output should be 'This is Kyle.' instead of 'This is [Cole].'

Cole Perry
  • 333
  • 1
  • 5
  • 27
  • 1
    Use regex syntax: `var regex = /\[(.*?)\]/;` — use a string, it's parsed as such and the backslashes will be "eaten". – Pointy Jan 21 '20 at 21:31
  • I literally just tried this before I saw your comment. I feel dumb. Regret posting. Maybe someone else will see this and it'll help them though. – Cole Perry Jan 21 '20 at 21:37

3 Answers3

0

The only thing that needs fixed is the regex string needs to be

var regex = /\[(.*?)\]/gm;

The /gm on the end just means it wont stop at the first one it finds and the "m" stands for multi-line matching.

Cole Perry
  • 333
  • 1
  • 5
  • 27
0

The javascript string replace can accept both strings and regular expressions as the first argument. See the examples presented here.

In your case you are passing the first as a string of a regular expression: "\[(.*?)\]"

Instead you should either match the exact string sentence.replace("[Cole]", names[1]) or, what you probably want, is to use the regular expression to match any name sentence.replace(/\[.+\]/g, names[1]) (note that the first argument does not contain any quotes)

The /g (global) is used to match all occurrences in the sentence. Otherwise only the first occurrence would be replaced.

0

Could you try this :

function replacingText() {
  var names = ["Cole", "Kyle", "Chase"];
  var sentance = "This is [Cole] [ahmed]";
  var regex = /\[([0-9]|[aA-zZ])*\]/g;
  console.log(sentance.replace(regex, names[1]));
}

I just tried it and it works as expected

Ahmed Kesha
  • 810
  • 5
  • 11