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
You could use
RegExp
/(\[~)|(\])/g
You need to qualify the tilde in the search. I'm surprised at all the crazy down voting. People are trying to be helpful here. If someone has a problem with the post and the answers, it's more helpful to explain WHY you downvote and not just go willy-nilly on the down-votes without explaining yourself.
As others have said, google is a friend. Try searching through www.regular-expressions.info for more help.
The code below uses Regexp to find all group of sequences that start with [~ and end with ]. It also captures the word in between. $1 in the second parameter of replace function references the found word.
I think this is what you are looking for https://jsfiddle.net/DIRTY_SMITH/7oe5kh9L/33/
string.replace(/\[~/g, '@').replace(/\]/g, '');
The issue is a bit more complicated than simply nesting
.replace
[@
and]
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:
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 least1
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
ormedia
p3
contains the]
The
return
statementreturn
s an@
, followed by the word between the[~
and]
This will replace all
[~
with@
Here is a working example:
Edit: Actually, you can make it simpler:
Check out the demo below:
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