I have multiple types of strings in Arraylist. ( Similarly same pattern )
var arrStr = [
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00 PROF 10',
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00PROF 10' ,
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00Profit 10',
'Slab3 - Slab 1.00 NAV & Slab14- Slab 10.00 PROF 12',
'Slab3 - Slab 1.00 NAV & Slab14- Slab 18.00PROF 12',
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00Profit 12',
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00 Profit 12'
]
Here I need to get data before and after from Prof. For Ex:
let txt1 = 'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00 PROF 10'
// i need the 20.00 and 10 ( 20.00 PROF 10 )
// but some time the pattern is coming with different format.
// As like
**20.00PROF 10**
**20.00Profit 10**
**10.00 PROF 12**
**18.00PROF 12**
**20.00Profit 12**
**20.00 Profit 12**
Don't have ab idea to take the data from this string. Please help me to solve this issue. Solution codes are welcome.
Try a regex.
arrStr.forEach((s) => console.writeLine(s.toLowerCase().match(/(\d+\.\d{2})prof\S*\s*(\d+)/)));
var randomString = "Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00 PROF 10";
// you can use above any string
Explode your string with space, store array into your any variable:
var randomStringArray = randomString.split(" ");
In your given string there is some common thing is that your required value. It is in the end of the string so we can get profit easily. For slab, we have to check if either the second to last is the value or the third from the last is the number value. So we use ternary operator example given below.
Here is the way to use a ternary and find the slab:
var slab = (parseFloat(randomStringArray[randomStringArray.length - 2])) ? parseFloat(randomStringArray[randomStringArray.length - 2]) : parseFloat(randomStringArray[randomStringArray.length - 3]);
Here is the way to get the last value as a profit:
var profit = parseFloat(randomStringArray[randomStringArray.length - 1]);