I've a string something like
<dt>Source:</dt>
<dd>
Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p
</dd>
Now I am a regex to fetch different values for it, i.e. : Volume, issue, date etc
so, I fetch entire text using :
var attr = jQuery("dl dt:contains('Source:') ~ dd:eq(0)").text();
And use regex to fetch different values, such as :
To fetch start page I use, following regex:
var regex = new RegExp("p\\d+(?=[-\\s]{1})");
var regexValPS = attr.match(regex);
Return value : p120, expected : 120
Similarly, to fetch Volume info, I use following, regex:
var regexVol = new RegExp("Vol.\\s\\d+");
var regexValVol = attributeVal.match(regexVol);
I get : Vol. 9 , I want : 9
Similarly I am getting issue number with "Issue" text :
var regEx = new RegExp("Issue\\s\\d+");
var regExVal = attributeVal.match(regEx);
I Should get : 30 instead : Issue 30
The problem is I can't use another regex to get the desired value, can't strip/parseInt etc, and the pattern must be able to fetch information in a single regex.
Use grouping (...) and read its match ยป
Demo:
var str = "Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p";
var re = /p(\d+)(?=[\-\s])/;
document.writeln(re.exec(str)[1]); // prints: 120
re = /Vol\.\s(\d+)/;
document.writeln(re.exec(str)[1]); // prints: 9
Test it here.
Toget the desired info using a single regex, you need to take advantage of regex grouping:
var regEx = new RegExp("Issue\\s(\\d+)");
var regExVal = attributeVal.match(regEx)[1];
If you cannot modify the regex, you can maybe parse the resulting number :
var number = "Issue 30".replace(/\D/g, '');
If I understand you correctly, you do not want to do further parsing on the string values returned by the .match() calls, but can accept a different regular expression if it returns the necessary values in one statement.
Your regex needs a capture group () to retrieve the desired numbers, and place them in an array index [] (the first index [0] will hold the entire matched string, and subsequent indices hold the () captured substrings).
Instead of new RegExp() you can use the simpler /pattern/ regex literal in this case, and it is possible to extract the desired value in a single statement for all cases.
var yourString = '<dt>Source:</dt>\
<dd>\
Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p\
</dd>';
// Match the page, captured in index [1]
yourString.match(/p(\d+)(?=[-\s]{1})/)[1];
// "120"
// Match the Vol captured in index [1]
yourString.match(/Vol\.\s(\d+)/)[1];
// "9"
// Match the issue captured in index [1]
yourString.match(/Issue\s(\d+)/)[1];
// "30"
Here it is on jsfiddle
Try this:
var attr = jQuery("dt:contains('Source:') ~ dd:eq(0)").text();
console.log(attr);
console.log(attr.match(/p(\d+)(?=[-\s]{1})/)[1]);
console.log(attr.match(/Vol\.\s(\d+)/)[1]);
console.log(attr.match(/Issue\s(\d+)/)[1]);
For more details: JQUERY REGEX EXAMPLES TO USE WITH .MATCH().
Related
I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)
I have a string like this:
20 EQUALS 'Value goes here'
I want to split it up into 3 separate strings:
conditionField = 20
conditionOperation = 'EQUALS'
conditionValue = 'Value goes here'
I tried this to get the Condition Field:
var conditionField = condition.replace(/(.*)(.*EQUALS)/, '$1');
But it get's the beginning and the end.
I'm having trouble splitting it up and dealing with the white space and spaces in the value.
Your question would actually be a bit of challenge if you wanted to arbitrarily extract quoted terms along with individual words. But since you appear to have a rather fixed structure, starting with a single number, then a single word command, followed by a third term, we can use the following regex pattern here:
([^\\s]*)\\s+([^\\s]*)\\s+(.*)
Each term in parentheses above will be made available as a capture group after the match has been run. In this case, I just blanket everything after the first two terms together.
var string = "20 EQUALS 'Value goes here'";
var re = new RegExp("([^\\s]*)\\s+([^\\s]*)\\s+(.*)");
match = re.exec(string);
if (match != null) {
console.log(match[1])
console.log(match[2])
console.log(match[3])
}
Try this :
var data = '20 EQUALS 30';
var a = data.split(/(\d*) ([a-zA-Z]*) (\d*)/g);
conditionField = a[1];
conditionOperation = a[2];
conditionValue = a[3];
I have a number returned from the database
e.g.
329193914
What I would like to do it simply be able to just insert dashes every 3 characters.
e.g.
329-193-914
I was looking at regex, replace and slice , slice I had a hard time with as a lot of example are like f.value and i'm not passing in "this" (entire element)
if your number can be treated as a string:
var str = '329193914';
var arr = str.match(/.{3}/g); // => ['329', '193', '914']
var str2 = arr.join('-'); // => '329-193-914'
I need to remove the dot in 1.400 in order to get the integer 1400, but it return 140. How do I obtain 1400 as an integer?
var var2= String(1.400) ;
var2 = var2.replace(".","");
var2=parseInt(var2);
There's no way the code you've given returns 140, since 1.400 is a number literal and gets shortened to 1.4 straight away and only then turned to string of "1.4". Therefore replacing a dot and converting to int results in 14.
It's not possible to tell JavaScript that number of 1.400 is not 1.4. You'd have to start with a string of "1.400" to get what you want.
Instead of going number -> string -> number maybe you could multiply the number by a thousand, or whatever order of magnitude is required.
Here is the problem ,
var var2= String(1.400) ;
alert(var2); //Returns 1.4 cause it is performing Number to String conversion
So , Change it to var var2= "1.400"; or var var2=number.toString();
And Update the replace to
var2.replace(/\./g,""); // : /g means all occurrence
You need to escape the . because it has the meaning of an arbitrary character in a regex.
Using this you will get your expected output.
var var2= "1.400" ;
var2 = var2.replace(".","");
var2=parseInt(var2);
Explanation:
var s1 = '2 + 2'; // creates a string primitive
var s2 = new String('2 + 2'); // creates a String object
console.log(eval(s1)); // returns the number 4
console.log(eval(s2)); // returns the string "2 + 2"
Add single-quotes around the initial string:
var var2= String('1.400');
the string looks like this
"blabla blabla-5 amount-10 blabla direction-left"
How can I get the number just after "amount-", and the text just after "direction-" ?
This will get all the numbers separated by coma:
var str = "10 is smaller than 11 but greater then 9";
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
After execution, the string matches will have values "10,11,9"
If You are just looking for thew first occurrence, the pattern will be /[0-9]+/ - which will return 10
(There is no need for JQuery)
This uses regular expressions and the exec method:
var s = "blabla blabla-5 amount-10 blabla direction-left";
var amount = parseInt(/amount-(\d+)/.exec(s)[1], 10);
var direction = /direction-([^\s]+)/.exec(s)[1];
The code will cause an error if the amount or direction is missing; if this is possible, check if the result of exec is non-null before indexing into the array that should be returned.
You can use regexp as explained by w3schools. Hint:
str = "blabla blabla-5 amount-10 blabla direction-left"
alert(str.match(/amount-([0-9]+)/));
Otherwize you can simply want all numbers so use the pattern [0-9]+ only.
str.match would return an array.