How to find multiple values between two character in a string - JS - javascript

I have a string that I am trying to retrieve a value from between two certain characters. I know there are multiple questions like this on here, but I couldn't find one that searches for multiple instances of this scenario in the same string.
Essentially I have a string like this:
'(value one is: 100), (value two is:200)'
and I want to return both 100 and 200. I know that I can write a regex to retrieve content between two characters, but what is the best way to have a function iterate over the string for the : character and grab everything from that until the ) character and only stop when there are no more instances?
Thanks in advance!

For your case, you can use regex to get the numbers from string.
var str = '(value one is: 100), (value two is:200)';
var regex = /\d+/g;
str.match(regex);
Here \d+ will match the numbers from string. g is global flag to match all the elements and not the only first.
Demo: http://jsfiddle.net/tusharj/k96y3evL/

Using Regex
var regex = /\d+/g;
var string = '(value one is: 100), (value two is:200)';
var match = string.match(regex);
alert(match);
Fiddle

Related

Javascript RegEx contains

I'm using Javascript RegEx to compare if a string matches a standart format.
I have this variable called inputName, which has the following format (sample):
input[name='data[product][tool_team]']
And what I want to achieve with Javascript's regex is to determine if the string has the following but contains _team in between those brackets.
I tried the following:
var inputName = "input[name='data[product][tool_team]']";
var teamPattern = /\input[name='data[product][[_team]]']/g;
var matches = inputName.match(teamPattern);
console.log(matches);
I just get null with the result I gave as an example.
To be honest, RegEx isn't really my area, so I suppose it's wrong.
A couple of things:
You need to escape [ and ] as they have special meaning in regex
You need .* (or perhaps [^[]*) in front of _team if you want to allow anything there ([^[]* means "anything but a [ repeated zero or more times)
Example if you just want to know if it matches:
var string = "input[name='data[product][tool_team]']";
var teamPattern = /input\[name='data\[product\]\[[^[]*_team\]'\]/;
console.log(teamPattern.test(string));
Example if you need to capture the xyz_team bit:
var string = "input[name='data[product][tool_team]']";
var teamPattern = /input\[name='data\[product\]\[([^[]*_team)\]'\]/;
var match = string.match(teamPattern);
console.log(match ? match[1] : "no match");
If you are trying to check for DOM elements you can use attribute contains or attribute equals selector
document.querySelectorAll("input[name*='[_team]']")

How to create a regex that checks the string contains specific pattern in javascript?

I have a requirement where I need to traverse through the string and get the first occurrence of a specific pattern like as follows,
i am a new **point**
On the occurrence of two consecutive character it must return true.
I must *not* be returned or*
The above pattern must return false.I tried to create regex following few links but the string.match method always returns null.
My code,
var getFormat = function(event) {
var element = document.getElementById('editor');
var startIndex = element.selectionStart;
var selectedText = element.value.slice(startIndex);
var regex = new RegExp(/(\b(?:([*])(?!\2{2}))+\b)/)
var stringMatch = selectedText.match(regex);
console.log('stringMatch', stringMatch);
}
<html>
<body>
<textarea onclick='getFormat(event);' rows='10' cols='10' id='editor'></textarea>
</body>
</html>
As I am new to regex I couldn't figure out where I am wrong.Could anyone help me out with this one?
On the occurrence of two consecutive character it must return true.
If I'm understanding you correctly. You just want to check if a string contains two consecutive characters, no matter which character. Then It should be enough doing:
(.)\1
Live Demo
This is of course assuming that it's literally any character. As in two consecutive whitespaces also being a valid match.
If you just need to check if there's two stars after each other. Then you don't really need regex at all.
s = "i am a new **point**";
if (s.indexOf("**") != -1)
// it's a match
If it's because you need the beginning and end of the two stars.
begin = s.indexOf("**");
end = s.indexOf("**", begin + 1);
Which you with regex could do like this:
((.)\2)(.*?)\1
Live Demo

How to split a string by a character not directly preceded by a character of the same type?

Let's say I have a string: "We.need..to...split.asap". What I would like to do is to split the string by the delimiter ., but I only wish to split by the first . and include any recurring .s in the succeeding token.
Expected output:
["We", "need", ".to", "..split", "asap"]
In other languages, I know that this is possible with a look-behind /(?<!\.)\./ but Javascript unfortunately does not support such a feature.
I am curious to see your answers to this question. Perhaps there is a clever use of look-aheads that presently evades me?
I was considering reversing the string, then re-reversing the tokens, but that seems like too much work for what I am after... plus controversy: How do you reverse a string in place in JavaScript?
Thanks for the help!
Here's a variation of the answer by guest271314 that handles more than two consecutive delimiters:
var text = "We.need.to...split.asap";
var re = /(\.*[^.]+)\./;
var items = text.split(re).filter(function(val) { return val.length > 0; });
It uses the detail that if the split expression includes a capture group, the captured items are included in the returned array. These capture groups are actually the only thing we are interested in; the tokens are all empty strings, which we filter out.
EDIT: Unfortunately there's perhaps one slight bug with this. If the text to be split starts with a delimiter, that will be included in the first token. If that's an issue, it can be remedied with:
var re = /(?:^|(\.*[^.]+))\./;
var items = text.split(re).filter(function(val) { return !!val; });
(I think this regex is ugly and would welcome an improvement.)
You can do this without any lookaheads:
var subject = "We.need.to....split.asap";
var regex = /\.?(\.*[^.]+)/g;
var matches, output = [];
while(matches = regex.exec(subject)) {
output.push(matches[1]);
}
document.write(JSON.stringify(output));
It seemed like it'd work in one line, as it did on https://regex101.com/r/cO1dP3/1, but had to be expanded in the code above because the /g option by default prevents capturing groups from returning with .match (i.e. the correct data was in the capturing groups, but we couldn't immediately access them without doing the above).
See: JavaScript Regex Global Match Groups
An alternative solution with the original one liner (plus one line) is:
document.write(JSON.stringify(
"We.need.to....split.asap".match(/\.?(\.*[^.]+)/g)
.map(function(s) { return s.replace(/^\./, ''); })
));
Take your pick!
Note: This answer can't handle more than 2 consecutive delimiters, since it was written according to the example in the revision 1 of the question, which was not very clear about such cases.
var text = "We.need.to..split.asap";
// split "." if followed by "."
var res = text.split(/\.(?=\.)/).map(function(val, key) {
// if `val[0]` does not begin with "." split "."
// else split "." if not followed by "."
return val[0] !== "." ? val.split(/\./) : val.split(/\.(?!.*\.)/)
});
// concat arrays `res[0]` , `res[1]`
res = res[0].concat(res[1]);
document.write(JSON.stringify(res));

Match a string between two other strings with regex in javascript

How can I use regex in javascript to match the phone number and only the phone number in the sample string below? The way I have it written below matches "PHONE=9878906756", I need it to only match "9878906756". I think this should be relatively simple, but I've tried putting negating like characters around "PHONE=" with no luck. I can get the phone number in its own group, but that doesn't help when assigning to the javascript var, which only cares what matches.
REGEX:
/PHONE=([^,]*)/g
DATA:
3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756,
MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802,
GENDER=0, CITY=, LASTNAME=Morgan
The way you're doing it is right, you just have to get the value of the capture group rather than the value of the whole match:
var result = str.match(/PHONE=([^,]*)/); // Or result = /PHONE=([^,]*)/.exec(str);
if (result) {
console.log(result[1]); // "9878906756"
}
In the array you get back from match, the first entry is the whole match, and then there are additional entries for each capture group.
You also don't need the g flag.
Just use dataAfterRegex.substring(6) to take out the first 6 characters (i.e.: the PHONE= part).
Try
var str = "3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756, MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802, GENDER=0, CITY=, LASTNAME=Morgan";
var ph = str.match(/PHONE\=\d+/)[0].slice(-10);
console.log(ph);

JavaScript escape stars on regular expression

I am trying to get a serial number from a zigbee packet (i.e get from 702442500 *13*32*702442500#9).
So far, I've tried this:
test = "*#*0##*13*32*702442500#9##";
test.match("\*#\*0##\*13\*32\*(.*)#9##");
And this:
test.match("*#*0##*13*32*(.*)#9##");
With no luck. How do I get a valid regular expression that does what I want?
The below regex matches the number which has atleast three digits,
/([0-9][0-9][0-9]+)/
DEMO
If you want to extract the big number, you can use:
/\*#\*0##\*13\*32\*([^#]+)#9##/
Note that I use delimiters / that are needed to write a pattern in Javascript (without the regexp object syntax). When you use this syntax, (double)? quotes are not needed. I use [^#]+ instead of .* because it is more clear and more efficent for the regex engine.
The easiest way to grab that portion of the string would be to use
var regex = /(\*\d{3,}#)/g,
test = "*13*32*702442500#9";
var match = test.match(regex).slice(1,-1);
This captures a * followed by 3 or more \d (numbers) until it reaches an octothorpe. Using the global (/g) modifier will cause it to return an array of matches.
For example, if
var test = "*13*32*702442500#9
*#*0##*13*32*702442500#9##";
then, test.match(regex) will return ["*702442500#", "*702442500#"]. You can then slice the elements of this array:
var results = [],
test = "... above ... ",
regex = /(\*\d{3,}#)/g,
matches = test.match(regex);
matches.forEach(function (d) {
results.push(d.slice(1,-1));
})
// results : `["702442500", "702442500"]`

Categories

Resources