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:
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
[~sample]to@smapleor to@sample? I'm asking just to be sure it was a typo