1

If I have the following string

"[Blah][Something.][Where.]"

What is the best way to locate wherever the "][" is and add a " + " in between them?

In other words, the resulting string should be:

"[Blah] + [Something.] + [Where.]"
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • Look here: http://stackoverflow.com/questions/4313841/javascript-how-can-i-insert-a-string-at-a-specific-index This was already posted in the past. – JohannesB Dec 14 '12 at 15:46
  • 1
    Damascusi isn't asking about inserting characters as specific string indices, but rather, finding a pattern and replacing it with something else. – Julian H. Lam Dec 14 '12 at 15:49

4 Answers4

2

Using regular expressions...

var str = "[Blah][Something.][Where.]"
var newString = str.replace(/\]\[/g, ']+[');

Relevant jsFiddle

Julian H. Lam
  • 25,501
  • 13
  • 46
  • 73
1

I'd use split and join.

var string = "[Blah][Something.][Where.]".split("][").join("] + [");

http://jsfiddle.net/tDFh3/4/

If it was not a constant string, I would fallback to a regular expression and replace.

gpojd
  • 22,558
  • 8
  • 42
  • 71
0

Use regular expresions to find ][ and then add +

David Strada
  • 130
  • 11
0

What about a regex:

  • search for \]\[
  • replace by ] + [

Demo

sp00m
  • 47,968
  • 31
  • 142
  • 252