Javascript Regex - Get All string that has square brackets [] - javascript

I have string data below:
var data = "somestring[a=0]what[b-c=twelve]----[def=one-2]test"
I need to get all strings that contain square brackets []. This is the result that I want.
["[a=0]", "[b-c=twelve]", "[def=one-2]"]
I've tried using regex /\[(.*?)\]/, but what I've got is an only the first array element is correct, the next elements are basically the same value but without the square brackets.
data.match(/\[(.*?)\]/);
// result => ["[a=0]", "a=0"]
What regexp should I use to achieve the result that I want? Thank you in advance.

You want to use the g (global) modifier to find all matches. Since the brackets are included in the match result you don't need to use a capturing group and I used negation instead to eliminate the amount of backtracking.
someVar.match(/\[[^\]]*]/g);

In /\[(.*?)\]/, *? means lazy, matching as few content as possible.
What you actually want is all the matches in content. Try modifier g
Try this one, http://regex101.com/r/aD6cM8/1. Any match starts with [, ends with ], but doesn't allow[ or ] inbetween.
someVar.match(/\[([^\[\]]*)\]/g)

You should just add the g switch to your regex :
someVar.match(/\[(.*?)\]/); // result => ["[a=0]", "a=0"]
results in
[ "[a=0]", "[b-c=twelve]", "[def=one-2]" ]

Your regex is correct, just suffix g to it to make it global:
someVar.match(/\[(.*?)\]/g);
Here's more info on it: http://www.w3schools.com/jsref/jsref_regexp_g.asp

Related

How to delete brackets after a special letter in regex

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]
Here is the link of the regex
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);
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)
})
let name = "#[something_here]"
name.replace(/(\[|\])/, "")

How to get the 1st character after a pattern using regex?

I'm trying to get the first character after the pattern.
i.e.
border-top-color
padding-top
/-[a-z]/g
selects:
border[-t]op[-c]olor
padding[-t]op
I want to select:
border-[t]op-[c]olor
padding-[t]op
How do you just get the first character after a selected pattern?
Example Here! :)
To get the t after border-, you usally match with this kind of regex:
border-(.)
You can then extract the submatch:
var characterAfter = str.match(/border-(.)/)[1];
match returns an array with the whole match as first element, and the submatches in the following positions.
To get an array of all the caracters following a dash, use
var charactersAfter = str.match(/-(.)/g).map(function(s){ return s.slice(1) })
Just use a capturing group:
"border-top-color".replace(/-([a-z])/g, "-[$1]")
Result:
"border-[t]op-[c]olor"
You can use submatching like dystroy said or simply use lookbehind to match it:
/(?<=-)./

How to get value without brackets using JQuery plugin inputmask?

There is the following code:
$("#ce_clientphone").inputmask("+9(999)9999999")
...
console.log($('#ce_clientphone').unmask())
As you can see I try to get value from '#ce_clientphone' without brackets. How can I do it? I need to allow user to input valid phone, but to save it in the database I need to remove brackets. Thanks in advance.
You could do regular expressions and replace to remove the brackets
"+9(999)9999999".replace(/[()]/g,'');
var str="+9(999)9999999";
alert(str.replace(/[()]/g,''));
DEMO
Try this:
$('#ce_clientphone').unmask().replace(/[()]/g, '');
For example:
"+9(999)9999999".replace(/[()]/g, '');
Returns:
"+99999999999"
So, how does this work?
We're using a regex to replace the brackets:
/ // Start of regex
[ // Start of character group
() // match either of these characters in the group (So match `(` OR `)`)
] // End of character group
/ // End of regex
g // `Global` flag. This means the regex won't stop searching after the first replace

Extract specific chars from a string using a regex

I need to split an email address and take out the first character and the first character after the '#'
I can do this as follows:
'bar#foo'.split('#').map(function(a){ return a.charAt(0); }).join('')
--> bf
Now I was wondering if it can be done using a regex match, something like this
'bar#foo'.match(/^(\w).*?#(\w)/).join('')
--> bar#fbf
Not really what I want, but I'm sure I miss something here! Any suggestions ?
Why use a regex for this? just use indexOf to get the char at any given position:
var addr = 'foo#bar';
console.log(addr[0], addr[addr.indexOf('#')+1])
To ensure your code works on all browsers, you might want to use charAt instead of []:
console.log(addr.charAt(0), addr.charAt(addr.indexOf('#')+1));
Either way, It'll work just fine, and This is undeniably the fastest approach
If you are going to persist, and choose a regex, then you should realize that the match method returns an array containing 3 strings, in your case:
/^(\w).*?#(\w)/
["the whole match",//start of string + first char + .*?# + first string after #
"groupw 1 \w",//first char
"group 2 \w"//first char after #
]
So addr.match(/^(\w).*?#(\w)/).slice(1).join('') is probably what you want.
If I understand correctly, you are quite close. Just don't join everything returned by match because the first element is the entire matched string.
'bar#foo'.match(/^(\w).*?#(\w)/).splice(1).join('')
--> bf
Using regex:
matched="",
'abc#xyz'.replace(/(?:^|#)(\w)/g, function($0, $1) { matched += $1; return $0; });
console.log(matched);
// ax
The regex match function returns an array of all matches, where the first one is the 'full text' of the match, followed by every sub-group. In your case, it returns this:
bar#f
b
f
To get rid of the first item (the full match), use slice:
'bar#foo'.match(/^(\w).*?#(\w)/).slice(1).join('\r')
Use String.prototype.replace with regular expression:
'bar#foo'.replace(/^(\w).*#(\w).*$/, '$1$2'); // "bf"
Or using RegEx
^([a-zA-Z0-9])[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#([a-zA-Z0-9-])[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
Fiddle

Regex thinks I'm nesting, but I'm not

I wrote this regexp to capture the strings below.
\!\[(.*?)?\]
All the strings below should match and return an optional string that's inside the first set of square brackets.
![]
![caption]
![]()
![caption]()
![caption][]
The problem is that this string also matches and returns ][ because the regex thinks it's between the first [ and last ].
![][] // Should not match, but does and returns "]["
How do I fix this?
Just remove the ? outside (.*?), that is redundant.
var myArray = ["![abc]","![caption]", "![def]()", "![caption]()","![caption][]"];
myArray.forEach(function(current) {
console.log(/!\[(.*?)\]/.exec(current)[1]);
});
Output
abc
caption
def
caption
caption
Check how the RegEx works here
Use this regex:
\!\[([^\]]*)\]
It means that it expects a "last" ] but makes internal ones invalid.
This should solve your issue.
My preference is this if you want to ignore catching the things like this ![[]]
\!\[([^\[\]]*)\]

Categories

Resources