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
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
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 _+ 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 substringp1 contains the [~p2 contains the word between the [~ and ], i.e. theme or mediap3 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With