Find string in array between other strings with javascript [duplicate] - javascript

This question already has answers here:
Regular expression to get a string between two strings in Javascript
(13 answers)
Get Substring between two characters using javascript
(24 answers)
Closed 2 years ago.
I have a text for example like this:
”Ordernumber 123888 Item 10 SCD”
This I load into an array.
What is the fastest way, to get the string between ”Ordernumber” and ”Item” out of this array? In this case the number ”123888”
I just started with js.
In my real project the text has multiple lines.
And out of it I have to get several other information also (sometimes the last strong, mostly between other strings which are always the same...)
In VBA I was able to load all the text into an array and wrote the VBA with find/search etc.
Now I want to transfer my tool to Google Sheets so I just started to learn/use Javascript.
Thanks in advance for your support and feedbacks go my first question in this community 👍

You could use a regex replacement:
var input = "Ordernumber 123888 Item 10 SCD";
var number = input.replace(/\bOrdernumber (\d+) Item\b.*/, "$1");
console.log(number);

Assuming the words are split using spaces, you can split the string and store it into an array.
const str = ”Ordernumber 123888 Item 10 SCD”; const data = str.split(' '); console.log(data[1]);
Now you can get the data by Index.

I think #Tim Biegeleisen using regex is better,
but another approach to achieve this is by getting the start index of "ordernumber" from the string, and then the same for "Item".
And by using String.prototype.substring(), and providing those indexes you can get the text between those words like so:
const str = "Ordernumber 123888 Item 10 SCD"
const res = str.substring(str.indexOf('Ordernumber') + 'Ordernumber'.length, str.indexOf('Item'));
console.log(res);
String.prototype.indexOf()
String.prototype.substring()

You can use .split () to get the string between one word or another, that way, you will also be able to access the properties of the informed quantity also if you want.
But realizing that it is a sales array, I suggest that you do a decapsulation of your object to be able to better manipulate the data and avoid losing them by being all in a single string.
let string = 'Ordernumber 123888 Item 10 SCD';
let result = string.split('Ordernumber').pop().split('Item')[0];
console.log(result);

I don't believe this is a good way of automating things. Searching in strings is prone to errors and is quite difficult to ensure you are extracting what you are really searching for. This is due to word repetitions etc.
However, one possible solution for you example above is using regular expressions. For your example you can use this (I put in purpose your string in an array as you said):
var c = [”Ordernumber 123888 Item 10 SCD”]
yourNumberThatYouWant = c[0].match(/Ordernumber (.*) Item/)[1]
This will work for short strings where you have these words only once. If you will have for instance the word "Item" repeating elsewhere the solution will bring everything between first instance of "Ordernumber" and last instance of "Item".

Related

is there a way to extract the number from .innerText

Lets say I've created some code where the user can keep adding numbers to a <ul> and next to each <li> is a delete button which can be used to remove said item off the list. The problem is for it to work each item on the list does not only contain a number it also contains some text. Lets just say:
<li>Bag of potatoes - 25kg</li>
is there any way that I can use .innerText on this list item, to then just extract the number 25 (or whatever number happens to be there) so that I can subtract it from the total.
I have tried the following:
const itemText = item.parentElement.innerText;
const itemWeight = itemText.match(/\d/g) || [];
However in this example it returns 2,5 rather than 25. Is there a simple way I can convert the result 2,5 to 25, or is it possible to do this in a more efficient manner?
Thanks
parseInt() is pretty sweet
JS
const text = item.parentElement.innerText;
var number = parseInt(text.replace(/[^0-9\.]/g, ''), 10);
console.log(number)
parseInt() will process any string as a number and stop when it reaches a non-numeric character.
as #Zsolt mentions in the comments you should add \d+ where the + means matches the previous match (the \d one) one and unlimited time. so you will get all the numbers in the text.
const itemWeight = itemText.match(/\d+/g) || [];
I really encourage you to play around with this website regex101
it is designed to help you understand the regular expression and test them so on...
I hope that solves your problem. Thanks

Check if all elements in array are present in a string as words using regular expressions in Javascript

I have used existing Javascript functions that I found online but I need more control and I think regular expressions will allow it using flags to control if case sensitive or not, multiline etc.
var words=['one','two','cat','oranges'];
var string='The cat ate two oranges and one mouse.';
check=string.match(pattern);
pattern=???;
if(check!==null){
//string matches all array elements
}else{
//string does not match all array words
}
what would the pattern be and if it can be constructed using javascript using the array as a source?
***I will need to place the same function on the backend in PHP and so it would be easier just to create a regular expression and use it instead of looping and finding alternatives for this to work in PHP.
***I would love to have as many options including changes, replace, count and regular expressions are meant for this. And on the plus side the speed should be better using regex instead of looping(search the whole text for every element in the array) specially in case of a long array and a long string.
var words=['one','two','cat','oranges'];
let string='The cat ate two oranges and one mouse.';
words=words.map(function(value,index){return '(?=(.)*?\\b('+value+')\\b)'; }).join('');
let pattern=new RegExp(`${words}((.)+)`,'g');
if(string.match(pattern)!==null){
//string matches all elements
}else{
//string does not match all words
}
It will look for the exact word match, and you will have the extra control you wanted using regex flags for case insensitive..
if you want to test it or adjust it you can do it here:
doregex.com
You can use the same regex to make changes within the text using a callback function.
You can create RegExp objects from your strings, this will allow you further control over case sensitivity etc.
For example:
const patterns = [ 'ONE','two','cat','oranges'];
const string = 'The cat ate two oranges and one mouse.';
// Match in a case sensitive way
const result = patterns.every(pattern => new RegExp(pattern, 'i').test(string));
console.log("All patterns match:", result);

Intersection of characters in two strings

I have an object with strings in it.
filteredStrings = {search:'1234', select:'1245'}
I want to return
'124'
I know that I can turn it into an array and then loop through each value and test if that value in inside of the other string, but I'm looking for an easier way to do this. Preferably with Lodash.
I've found _.intersection(Array,Array) but this only works with Arrays.
https://lodash.com/docs#intersection
I want to be able to do this without having to convert the object to an array and then loop through each value because this is going to be potentially holding a lot of information and I want it to work as quickly as possible.
Thank you for you help.
Convert one of the strings (search) to a RegExp character set. Use the RegExp with String#match on the other string (select).
Note: Unlike lodash's intersection, the result characters are not unique, so for example 4 can appear twice.
var filteredStrings = {search:'1234', select:'124561234'}
var result = (filteredStrings.select.match(new RegExp('[' + filteredStrings.search + ']', 'g')) || []).join('');
console.log(result);

wildcard search (?, *) in a string array using javascript

I am trying to achieve wild card search on a string array using java script
Here the wild cards i use are ? -to represent single char and * to represent multiple char
here is my string array
var sample = new Array();
sample[0] = 'abstract';
sample[1] = 'cabinet';
sample[2] = 'computer';
For example i searched for a string 'ab*t' in the array and the regular expression I used for this is '\ab.*t\', but the problem is I get both 'abstract' and 'cabinet' as matching strings. I only want the string that starts with 'ab' and not where it comes in the middle.
So I modified my regexp like this '\^ab.*t$\ but still the same result. So can somebody give me some tips on how this can be achieved.
You are using using wrong wrong slashs you should use forward slash('/') instead of backward slashs ('\')
probably it'll help you /^ab.*t$/

Parse string regex for known keys but leave separator

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"]

Categories