Skip to content Skip to sidebar Skip to footer

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 stri

Solution 1:

Using regular expressions...

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

Relevant jsFiddle

Solution 2:

I'd use split and join.

varstring = "[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.

Solution 3:

Use regular expresions to find ][ and then add +

Solution 4:

What about a regex:

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

Demo

Post a Comment for "Best Way To Insert Char In Specific Points Of String In Javascript?"