Rolando
Rolando

Reputation: 62674

Best way to insert char in specific points of string in javascript?

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.]"

Upvotes: 1

Views: 2764

Answers (4)

gpojd
gpojd

Reputation: 23075

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.

Upvotes: 1

sp00m
sp00m

Reputation: 48837

What about a regex:

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

Demo

Upvotes: 0

Julian H. Lam
Julian H. Lam

Reputation: 26134

Using regular expressions...

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

Relevant jsFiddle

Upvotes: 2

David Strada
David Strada

Reputation: 130

Use regular expresions to find ][ and then add +

Upvotes: 0

Related Questions