Good morning, I want to find out in javascript with a query if a short string is included in a model number. The code now looks like this:
(ui.item.Partnumber).includes("C-")
But now I want to find out
- if there is a number before the
C
- and a letter after the
-
.
Unfortunately I can't find anything on the web. Would that be possible with ${..} ? But also for this I found too little that it could help me. Can someone help me please?
CodePudding user response:
You can use a regular expression to test for those patterns.
The regex says:
Find a digit (
\d
) followed byC-
followed by a letter from[A-Z]
.
If that's the entirety of the string you can bookend the regex with ^
(start of the string) and $
(end of the string). If you're looking to find uppercase or lowercase letters you can use [A-Za-z]
instead.
const re = /\dC-[A-Z]/;
console.log(re.test('1C-3'));
console.log(re.test('1C-F'));
console.log(re.test('1C3'));
console.log(re.test('1F-3'));
console.log(re.test('6C-V'));
console.log(re.test('3C-T'));
CodePudding user response:
let str = "3C-a";
let pattern = /^\d C-[a-zA-Z]$/;
let result = pattern.test(str);
console.log(result); // true
The regular expression /^\d C-[a-zA-Z]$/ checks if the string starts with one or more digits (\d ), followed by the letter "C", then a hyphen, and finally ends with a letter ([a-zA-Z]).
CodePudding user response:
Regex will be best (see other answers)
But if you want to get number before and after do this. Use split
and check the first and second array elements.
var result = ("123C-324").split("C-");
console.log(result);