I have a string that will be formatted something like ___<test#email.com>____ where the underscores is irrelevant stuff I don't need but varys in length. I need to select and store what is between the brackets.
My problem is that all of the sub string solutions I have seen operate off of a hard integer location in the string. But the start and end of the substring I want to select (the brackets) will never be the same.
So I thought if I could use something to find the location of the brackets then feed that to a substring solution that would work. But all of the ways I have found of identifying special characters only reports if there are special characters, not where they are.
Thanks in advance!
based on this answer
var text = '___<test#email.com>____';
var values = text.split(/[<>]+/);
console.log(values); // your values should be at indexes 1, 3, 5, etc...
Here's a regex that should set you on your way.
let string = "asdf asdf asdf as <thing#stuff.com> jl;kj;l kj ;lkj ;lk j;lk";
let myMatches = string.match(/<.*>/g);
let myMatch = myMatches[0].slice(1).slice(0,-1);
The .match function returns an array of matches, so you can find multiple <stuff> entries.
There's probably a way to do it without the slicing, but that's all I've got for now.
With Regex:
var myRe = /<(.*)>/g;
var myArray = myRe.exec("____<asdf>___");
if (myArray)
console.log(myArray[1]);
Regex test here
JSFiddle test here
Related
I am trying to fetch the value after equal sign, its works but i am getting duplicated values , any idea whats wrong here?
// Regex for finding a word after "=" sign
var myregexpNew = /=(\S*)/g;
// Regex for finding a word before "=" sign
var mytype = /(\S*)=/g;
//Setting data from Grid Column
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
var newtype = mytype.exec(strNew);
alert(matchNew);
https://jsfiddle.net/6vjjv0hv/
exec returns an array, the first element is the global match, the following ones are the submatches, that's why you get ["=20", "20"] (using console.log here instead of alert would make it clearer what you get).
When looking for submatches and using exec, you're usually interested in the elements starting at index 1.
Regarding the whole parsing, it's obvious there are better solution, like using only one regex with two submatches, but it depends on the real goal.
You can try without using Regex like this:
var val = 'QCById=20';
var myString = val.substr(val.indexOf("=") + 1);
alert(myString);
Presently exec is returning you the matched value.
REGEXP.exec(SOMETHING) returns an array (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec).
The first item in the array is the full match and the rest matches the parenthesized substrings.
You do not get duplicated values, you just get an array of a matched value and the captured text #1.
See RegExp#exec() help:
If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
Just use the [1] index to get the captured text only.
var myregexpNew = /=(\S*)/g;
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
if (matchNew) {
console.log(matchNew[1]);
}
To get values on both sides of =, you can use /(\S*)=(\S*)/g regex:
var myregexpNew = /(\S*)=(\S*)/g;
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
if (matchNew) {
console.log(matchNew[1]);
console.log(matchNew[2]);
}
Also, you may want to add a check to see if the captured values are not undefined/empty since \S* may capture an empty string. OR use /(\S+)=(\S+)/g regex that requires at least one non-whitespace character to appear before and after the = sign.
I try to get the 00-8.
Why this code do not returns me the 00-8 ?
<script>
var pageDetailsSecond = "a='00-8'b='13-'a+='00-2'b+='3333'c='4'";
var phone1 = pageDetailsSecond.match("a='(.*)'");
var phone1 = phone1[0];
var card_Phone = phone1;
alert(card_Phone);
</script>
Actually I get a='00-8'.
Because what you try to match includes a=....
But when you find it, you can strip it from the match found.
Checked with jsfiddle: http://jsfiddle.net/pbo5x9dx/
var pageDetailsSecond = "a='00-8'b='13-'a+='00-2'b+='3333'c='4'";
alert(pageDetailsSecond)
var phones = pageDetailsSecond.match("a='(.*?)'");
var phone1 = phones[1];
alert(phone1)
** edit: ** fix for non-greedy match, checked with http://jsfiddle.net/pbo5x9dx/1/
Because the array returned by match() will contain the entire match in the first array slot, and the capture groups in subsequent elements.
The array contents will be:
[
[0] = "a='00-8'",
[1] = '00-8'
]
What you want is phone1[1] instead of phone1[0], which contains just the portion of the match specified by your capture group (.*).
Based on the updated question, the regex pattern should be changed to:
"a='(.*?)'"
By default, regex patterns try to match as much as possible (known as "greedy"). The pattern is saying "match any number of any characters between ' characters. This now includes 00-8'b='13-'a+='00-2'b+='3333'c='4. By adding the ?, this changes the behaviour to "lazy". In other words, match as little as possible, and your regex is back to matching only 00-8 as before.
Ok, So I hit a little bit of a snag trying to make a regex.
Essentially, I want a string like:
error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z
to be parsed to read
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
ateTo=2013-01-16T05:00:00.000Z
So I want it to pull known keywords, and ignore other strings that have =.
My current regex looks like this:
(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=[\w\s\f\-\:]+(?![(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=])
So I'm using known keywords to be used dynamically so I can list them as being know.
How could I write it to include this requirement?
You could use a replace like so:
var input = "error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z";
var result = input.replace(/\s*\b((?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/g, "\n$1");
result = result.replace(/^\r?\n/, ""); // remove the first line
Result:
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
dateTo=2013-01-16T05:00:00.000Z
Another way to tokenize the string:
var tokens = inputString.split(/ (?=[^= ]+=)/);
The regex looks for space that is succeeded by (a non-space-non-equal-sign sequence that ends with a =), and split at those spaces.
Result:
["error=some=new item", "user=max", "dateFrom=2013-01-15T05:00:00.000Z", "dateTo=2013-01-16T05:00:00.000Z"]
Using the technique above and adapt your regex from your question:
var tokens = inputString.split(/(?=\b(?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/);
This will correctly split the input pointed out by Qtax mentioned in the comment: "error=user=max foo=bar"
["error=", "user=max foo=bar"]
I have strings in my program that are like so:
var myStrings = [
"[asdf] thisIsTheText",
"[qwerty] andSomeMoreText",
"noBracketsSometimes",
"[12345]someText"
];
I want to capture the strings "thisIsTheText", "andSomeMoreText", "noBracketsSometimes", "someText". The pattern of inputs will always be the same, square brackets with something in them (or maybe not) followed by some spaces (again, maybe not), and then the actual text I want.
How can I do this?
Thanks
One approach:
var actualTextYouWant = originalString.replace(/^\[[^\]]+\]\s*/, '');
This will return a copy of originalString with the initial [...] and whitespace removed.
This should get you started:
/(?:\[[^]]*])?\s*(\w+)/
I'm having real difficulty with this but I'm no javascript expert. All I want to do is get myself an array of all matches in a string which match a given regExp. The regExp being this :
[0-9]+
ie. Any integer.
So If I pass the string "12 09:8:76:::54 12" I should get
arr[0]="12"
arr[1]="09"
arr[2]="8"
arr[3]="76"
arr[4]="54"
arr[5]="12"
Easy? Not for me! I could do this in vb.net no problem with regexp.matches(string) (something like that anyway). I thought that the javascript method .exec would also give me an array however it only returns the first match. What's going on? Code...
function testIt(){
splitOutSelection2("123:::45 0::12312 12:17");
}
function splitOutSelection2(sSelection){
var regExp = new RegExp("[0-9]+","g");
var arr = regExp.exec(sSelection);
};
arr = sSelection.match(/[0-9]+/g);
should do.
g is the global modifier that you need to get all the matches, not just the first one.
something like:
var arrMatch = "12 09:8:76:::54 12".match(/[0-9]+/g);
alert(arrMatch);
.match will return an array if global is set (and matches are found of course).
[0-9]+ means it will search for not only single digits, but also match 12, 09, 76.
According to the doc, exec return the first match. You should use match instead.
var arr = sSelection.match(/[0-9]+/g);
or
var arr = sSelection.match(/\d+/g);
All the answers work but I was wanting to keep my regExp object rather than specify it at the time of use. So simply changing the function to...
function splitOutSelection2(sSelection){
var regExp = new RegExp("[0-9]+","g");
var arr = sSelection.match(regExp);
};
..is what I was looking for. Thanks for pointing me in the right direction though to all who have replied.
function splitOutSelection2(sSelection){
return sSelection.split(/[^0-9]+/g);
};
Negate the regExp and use String#split.