var string = "Administration for administering str1234 as an administrator";
I want to get the "str1234" only from the string variable. How do I do this?
Note that the index of substring "str1234" is not always consistent.
var string = "Administration for administering str1234 as an administrator";
I want to get the "str1234" only from the string variable. How do I do this?
Note that the index of substring "str1234" is not always consistent.
You can use Regular Expressions to search for patterns in strings.
To search for the pattern str followed by 1-4 numbers you would use the following expression:
\bstr\d{1,4}\b
Explanation of RegExp by regex101.com
\bassert position at a word boundary(^\w|\w$|\W\w|\w\W)
strmatches the charactersstrliterally (case sensitive) .
\d{1,4}matches a digit (equal to[0-9]) .
{1,4}Quantifier — Matches between 1 and 4 times, as many times as possible, giving back as needed (greedy) .
\bassert position at a word boundary(^\w|\w$|\W\w|\w\W)
In JavaScript:
let input = 'Administration for administering str1234 as an administrator';
let match = input.match(/\bstr\d{1,4}\b/);
The object match can be used like this:
match[0] // "str1234"
match.index // 33
match.input // "Administration for administering str1234 as an administrator"
Use indexof()
var string = "Administration for administering str1234 as an administrator";
var index; index= string.indexOf('str1234')
console.log(index)
To change 'str1234' to someother value ,you can use replace() .
Hope this helps :)
var string = "Administration for administering str1234 as an administrator";
var array = string.split(" ");
cont neededString;
for (const s of array) {
if(s.startsWith('str')){
neededString = s;
break;
}
//or
if(isAlphaNumeric(s))
{
neededString = s;
break;
}
}
public boolean isAlphaNumeric(String s){
String pattern= "^[a-zA-Z0-9]*$";
return s.matches(pattern);
}