Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - replace square brackets in a string

I have a simple string and trying to convert [~sample] to @sample. For example:

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology';
string.replace('[~', '@');

I have tried above solution but it only convert the first one and the ] can not be removed.


now I learnt how to use /g

like image 311
user3631047 Avatar asked Jul 21 '26 02:07

user3631047


2 Answers

The issue is a bit more complicated than simply nesting .replace [@ and ]

var string = 'Strategic [~theme] areas with cross [~media] technology [this is fine] ok?';

document.body.innerHTML = string.replace(/\[~([^\]]+)\]/g, '@$1');

The ([^\]]+) makes sure to capture any character that is not an ] but is delimited by [~ and ], which is a better solution in any case preventing text like [don't mess with me] to be... messed.

The RegExp is explained in detail here

like image 154
Roko C. Buljan Avatar answered Jul 23 '26 15:07

Roko C. Buljan


Try this code:

string.replace(/(\[~)(\w+)(\])/g, function(match, p1, p2, p3) {
  // p1 = [~
  // p2 = theme / media / whateverWord
  // p3 = ]
  return '@' + p2
  // Returns @whateverWord
})

In the 1st group:

  • \[ will select a [
  • ~ will select a ~

In the 2nd group:

  • \w will select any alphanumeric character or an _
  • The + states that the alphanumeric character must appear at least once, i.e. there must be at least 1 letter between the [~ and ]

In the 3rd group:

  • \] will select any ]

In the function:

  • match is not used in the output, but it contains the whole matched substring
  • p1 contains the [~
  • p2 contains the word between the [~ and ], i.e. theme or media
  • p3 contains the ]

The return statement returns an @, followed by the word between the [~ and ]

This will replace all [~ with @


Here is a working example:

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology. Also, [this tag] [will be kept]'

document.body.innerHTML = string.replace(/(\[~)(\w+)(\])/g, function(match, p1, p2, p3) {
  return '@' + p2
})

Edit: Actually, you can make it simpler:

string.replace(/(\[~)(\w+)(\])/g, '@$2')

Check out the demo below:

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology. Also, [this tag] [will be kept]'

document.body.innerHTML = string.replace(/(\[~)(\w+)(\])/g, '@$2')

The $2 contains the contents of the second capture group, and the second capture group contains the text between the [~ and ]. So the output is an @, followed by the text.

This is simpler and faster than the version above, and takes up less space

like image 29
Kaspar Lee Avatar answered Jul 23 '26 15:07

Kaspar Lee