I have a string value as abc:language-letters-alphs/EnglishData:7844val: . I want to extract the part language-letters-alphs/EnglishData, the value between first : and second :. Is there a way to do it without storing each substrings on different vars? I want to do it the ES6 way.
You can do this two ways easily. You can choose what suits you best.
Using String#split
Use split method to get your desired text.
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.
let str = 'abc:language-letters-alphs/EnglishData:7844val:'.split(':')
console.log(str[1]) //language-letters-alphs/EnglishData
Using String#slice
You can use [ Method but in that you have define the exact indexes of the words you want to extract.
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
let str = 'abc:language-letters-alphs/EnglishData:7844val:'
console.log(str.slice(4, 38)) //language-letters-alphs/EnglishData
const str = "abc:language-letters-alphs/EnglishData:7844val:"
const relevantPart = str.split(':')[1]
console.log("abc:language-letters-alphs/EnglishData:7844val:".split(":")[1])
Related
Say for example I have a array like this
var array = ['Value1', "ThisIsValue2", "AndThisIsValue3"]
I want to be able to check this array to look for the word And but nothing more once it checks all the values and it finds the one with the word And I want it to take that whole value and save it to another variable. How can I do this?
Try this, use array filter with includes:
let result = array.filter(v => v.includes('And'))
As I understood, you want to search in the array the word that contains "And" and return the whole word.
Easy way but not precise: search the word that contains "And" within any place in the string (ex "AndThisIsValue3", "ThisAndThat")
let result = array.find(w => /And/.test(w));
You can define the regular expression that fits fine with your purpose.
The variable result will store the first word that matches the regExp or undefined if no one does. If you need all matches, just use array.filter in the same way.
I have the following text string:
test-shirt-print
I want to filter the text string so that it only returns me:
test-shirt
Meaning that everything that comes after the second hyphen should be removed including the hyphen.
I am thinking that the solution could be to split on hyphen and somehow select the two first values, and combine them again.
I am unaware of which functionality is best practice to use here, I also thinking that if it would be possible to use a regular expression in order to be able to select everything before the second hyphen.
You can use split slice and join together to remove everything after the second hyphen
var str = "test-shirt-print";
console.log(str.split("-").slice(0, 2).join('-'))
You can try with String.prototype.slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
and String.prototype.lastIndexOf()
The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
var str = 'test-shirt-print';
var res = str.slice(0, str.lastIndexOf('-'));
console.log(res);
You can also use split() to take the first two items and join them:
var str = 'test-shirt-print';
var res = str.split('-').slice(0,2).join('-');
console.log(res);
How to get all text following the symbol ":"?
I have tried:
'prop:bool*'.match(/:(.[a-z0-9]+)/ig)
But it returns [":bool"] not ["bool"].
Update:
I need to use this inside the following expression:
'prop:bool*'.match(/^[a-z0-9]+|:.[a-z0-9]+|\*/ig);
So that the result becomes:
["prop", "bool", "*"]
You could solve this by performing a positive lookbehind action.
'prop:bool*'.match(/^[a-z0-9]+|(?<=:).[a-z0-9]+|\*/ig)
The positive lookbehind is the (?<=:) part of the regex and will here state a rule of must follow ':'.
The result should here be ["prop", "bool", "*"].
Edit:
Original requirements were somewhat modified by original poster to return three groups of answers. My original code, returning one answer, was the following:
'prop:bool*'.match(/(?<=:).[a-z0-9]+/ig)
This is not a pure regex solution since it takes advantage of the String Object with its substring() method, as follows:
var str = 'prop:bool*';
var match = str.match(/:(.[a-z0-9]+)/ig).pop().substring(1,str.length);
console.log(match);
When the match is successful, an array of one element will hold the value :bool. That result just needs to have the bool portion extracted. So, the element uses its pop() method to return the string value. The string in turn uses its substring() method to bypass the ':' and to extract the desired portion, namely bool.
var [a,b,c] = 'prop:bool*'.match(/^([a-z0-9]+)|:(.[a-z0-9]+)|(\*)/ig);
console.log(a,b.substring(1,b.length),c);
To return three groups of data, the code uses capture groups and trims off the colon by using the substring() method of b.
You could simply do:
'prop:bool*'.match(/:(.[a-z0-9]+)/)[1]
If your entire string is of the form you show, you could just use a regex with capture groups to get each piece:
console.log('prop:bool*'.match(/^([a-z0-9]+):(.[a-z0-9]+)(\*)/i).slice(1));
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);
How to use the javascript split splice slice methods to convert the:
1.18.0-AAA-1 into 1.18.0.
Start with the initial value, determine that the portion you want is before the first hyphen, so use that as the delimiter for the split. Perform the split and then the first portion will be everything up to but not including that first hyphen. You don't need slice or splice for this - just split. Then just add the dot at the end for the trailing dot.
var x="1.18.0-AAA-1";
var y=x.split("-");//splits it at each "-";
var z=y[0]+".";//gives 1.18.0.
however if you are asking to use each of the threeemethods to yield the outcome, then this sounds like homework and you should try doing it on your own. Best way to learn is to try.
Use split to create an array from your string
var str = "1.18.0-AAA-1";
var parts = str.split("-"); // this returns the array ["1.18.0", "AAA", "1"]
Now the easiest way to get what you want is doing:
parts[0];