Reputation: 77
Hi I am having problem while trying to remove these square brackets.
I figured out how to find square brackets but I need to find square brackets only if it starts with @ like this,
by the way I am using .replace to remove them in javascript, Not sure if it is going to help to find the answer.
@[john_doe]
The result must be @john_doe
.
I dont want to remove other brackets which is like that,
[something written here]
Upvotes: 3
Views: 86
Reputation: 19070
You can use Regular expression /@\[/g
:
const texts = ['@[john_doe]', '[something written here]']
texts.forEach(t => {
// Match the @ character followed by an opening square bracket [
const result = t.replace(/@\[/g, '@')
console.log(result)
})
Upvotes: 1
Reputation: 627086
You need a regular expression replace solution like
text = text.replace(/@\[([^\][]*)]/g, "@$1")
See the regex demo.
Pattern details
@\[
- a @[
text([^\][]*)
- Group 1 ($1
): any zero or more chars other than [
and ]
(the ]
is special inside character classes (in ECMAScript regex standard, even at the start position) and need escaping)]
- a ]
char.See the JavaScript demo:
let text = '@[john_doe] and [something written here]';
text = text.replace(/@\[([^\][]*)]/g, "@$1");
console.log(text);
Upvotes: 1