In string available only 3 parameters :
C1 - number is only 0 or 1
R1 - number is only 0 or 1
A
String Example
"C1-R1-C0-C0-A-R0-R1-R1-A-C1"
Smth like this /[CRA]\d-/gi only for each with separetor
OR better use split and map methods?
If you are looking for a regular expression, something like this should work:
/^([CR][01]|A)(-([CR][01]|A))*$/
Essentially, we match a valid "parameter" as well as any number of "-parameter" after it. In context:
const string1 = 'C1-R1-C0-C0-A-R0-R1-R1-A-C1';
const string2 = 'invalid';
const testString = (string) => {
return /^([CR][01]|A)(-([CR][01]|A))*$/.test(string);
};
console.log(testString(string1));
console.log(testString(string2));
Output:
true
false
Use split and then filter with the regexp.
let string = "C1-R1-C0-C0-A-R0-R1-R1-A-C1";
let result = string.split('-').filter(el => /^([CR][01]|A)$/.test(el));
console.log(result);
Related
I have a string like object/array nodes. need to convert string to nodes, using regular expression
const variableName = "parent1[0].child[2].grandChild['name'].deep_child"; // should be n number of child`
// expected result:
const array = ['parent1',0,'child',2,'grandChild','name','deepChild'];
// Note: array's strings property should be any valid variable name like 'parenet' or 'parent1' or 'PARENT' or '_parent_' or 'deep_child'
Note
You can get the desired result by using split
[^\w]
after splitting you may get empty strings so you can use a filter to filter out them. At last convert the required number that are in string to type number
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const result = variableName
.split(/[^\w]/)
.filter(_ => _)
.map(a => (isNaN(parseInt(a)) ? a : parseInt(a)));
console.log(result);
Try with regex /[\[\].']+/g.
Regex Evaluator.
This regex catches the group between [ and ]. and splits the string there. Also if ant node of the generated array is a number, convert that to a number using a map function.
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const output = variableName
.split(/[\[\].']+/g)
.map((node) => isNaN(node) ? node : Number(node));
console.log(output);
What you are looking for is a split of multiple conditions. A simple and good aproach is to replace all of them except one and finally make the split:
// should be n number of child`
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const array = variableName
.replaceAll("'", "")
.replaceAll("].", "[")
.split("[")
.map((x) => (isNaN(x) ? x : +x));
console.log(array);
This question already has answers here:
Counting the vowels in a string using Regular Expression
(2 answers)
Closed 1 year ago.
I tried to write a function which checks if a given string contains vowels and I cannot see why it works for some words 'cat' and 'why' but not 'DOG', i believe that i have accounted for uppercase.
const containsVowels = string => {
var lowerCase = string.toLowerCase();
var word = lowerCase.split("");
var vowelsArray = ["a","o","i","u","y"];
const result = word.filter(letter => vowelsArray.includes(letter));
return result.includes("a","o","i","u","y");
};
includes takes only 2 parameters, the first one being searchElement and second parameter being fromIndex.
Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#parameters
You wouldn't want to do the last check if the result array contains vowels or not, because in the previous step itself you are filtering out the word to get array that contains only vowels. So just check if the array is empty or it contains any elements inside it.
const containsVowels = str => {
let lowerCase = str.toLowerCase();
let word = lowerCase.split("");
let vowelsArray = ["a","o","i","u","y"];
const result = word.filter(letter => vowelsArray.includes(letter));
return result.length > 0;
};
console.log(containsVowels("cat"));
console.log(containsVowels("DOG"));
console.log(containsVowels("BCDF"));
Suggestion: Don't use built in keywords as variables.
As pointed out by Muhammad, we can regex to find if the string contains vowels
const containsVowel = str => {
const vowelRegex = /[aeiou]/i;
return vowelRegex.test(str);
};
2 Problems,
Why would you use includes twice ?
&
You cannot use includes like
result.includes("a","o","i","u","y");
includes only accepts 2 param:
includes(searchElement, fromIndex)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
By filtering, you already know the result.
What you should do is, compare the length of the result:
const containsVowels = string => {
let lowerCase = string.toLowerCase();
let word = lowerCase.split("");
let vowelsArray = ["a","o","i","u","y"];
const result = word.filter(letter => vowelsArray.includes(letter));
return result.length > 0 ? true : false
};
use regex to get the result.
var regEx = /[aeiou]/gi
var test_string = "Cat";
var match = test_string.match(regEx)
if(match)
console.log("Match found", match)
when you write something like this
result.includes("a","o","i","u","y")
this compare with only it's first element which is "a" and one thing you don't need to write the above mentioned code further.
After filtering just replace the above code with
return result.length > 0 ? true : false
I am tyring to reverse a string in javascript with the following code.
const reverseString = str => [...str].sort(() => 1).join('');
All my test are passing, except the one in which the string contains punctuations at the end. e.g hungry!, sharpshooter^. What is causing the error?
Test results
Input: "I am hungry!"
Expected: "!yrgnuh ma I"
Received: "u!Iyrgn h ma"
Input: "sharpshooter^"
Expected: "^retoohsprahs"
Received: "h^osaretorhsp"
I guess its because position in ASCII table, why wouldn't you use reverse() ?
const reverseString = str => [...str].reverse().join('')
You can use reverse() to reverse the array before joining the array elements.
function reverseString(str){
return [...str].reverse().join('');
}
console.log(reverseString("I am hungry!"));
console.log(reverseString("sharpshooter^"));
Try this:
const reverseString = str => [...str].sort(() => -1).join('');
or even better...
const reverseString = str => [...str].reverse().join('');
If you don't want to use split reverse and join, use a simple loop
function reverseString(str){
let length = str.length
let final = ''
while(length-- > 0){
final+= str[length]
}
return final
}
console.log(reverseString("I am hungry!"));
console.log(reverseString("sharpshooter^"));
What would be the best way to split an a string that a declaration of an array into an array of strings using javascript/jquery. An example of a string I am working with:
franchise[location][1][location_name]
I would like it to be converted into an array like:
['franchise', 'location', '1', 'location_name']
BONUS: If I could also get that numeric value to be an integer and not just a string in one fell swoop, that would be terrific.
You can use String.split with a regex that matches all the none alpha numeric chars.
Something like that:
const str = 'franchise[location][1][location_name]';
const result = str.split(/\W+/).filter(Boolean);
console.log(result);
One option would be to just match word characters:
console.log(
'franchise[location][1][location_name]'.match(/\w+/g)
);
To transform the "1" to a number, you might .map afterwards:
const initArr = 'franchise[location][1][location_name]'.match(/\w+/g);
console.log(initArr.map(item => !isNaN(item) ? Number(item) : item));
You could try
const str = 'franchise[location][1][location_name]';
const res = str.split(/\W+/).map(i => { return Number(i) ? Number(i) : i;})
so I am looking to get an specific numerical value using Javascript and regular expressions from a string like this: *#13**67*value##
So from
*#13**67*2##
*#13**67*124##
*#13**67*1##
I need to get 2, 124 and 1. Any help will be really appreciated. Thanks!
If your strings are always in this format, match the digits at the end of the string.
var r = '*#13**67*124##'.match(/\d+(?=#+$)/);
if (r)
console.log(r[0]); // => "124"
Multi-line matching:
var s = '*#13**67*2##\n*#13**67*124##\n*#13**67*1##',
r = s.match(/\d+(?=#+$)/gm)
console.log(r); // => [ '2', '124', '1' ]
Perhaps splitting the string?
var r = '*#13**67*124##'.split(/[*#]+/).filter(Boolean).pop()
console.log(r); // => "124"
function getValue(string) {
return parseInt(string.replace(/^.*(\d+)##$/gi, "$1"), 10);
}
This is a nice example for use regex lookahead.
You can use this regex:
\d+(?=##)
Working demo
How about this:
var regex = /^\*\#\d{2}\*{2}\d{2}\*(\d+)\#{2}$/;
var value = '*#13**67*124##'.match(regex)[1]; // value will be 124