I am going to find sequential string of numbers in string which starts from 1. For example I have this string.
"456000123456009123456780001234000"
Here sequential strings would be
"123456", "12345678", "1234"
How can I get above result using Javascript efficiently? The code looks like this.
findSequential("456000123456009123456780001234000");
//expected output
"123456", "12345678", "1234"
***note: "1" itself is not sequential, for example:
"3938139" - has no sequence
"39381249" - has "12"
With any language's solution would be appreciated but prefer Javascript or C. Thanks for your help!
push(char[i]); } else { tempArry[char[i]] = []; tempArry[char[i]]. push(char[i]); } } console. log(tempArry); This will even return the number of repeated characters also.
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
A string is a sequence of characters. You can access the characters one at a time with the bracket operator: >>> fruit = 'banana' >>> letter = fruit[1] The second statement extracts the character at index position 1 from the fruit variable and assigns it to the letter variable.
A simple for loop should be able to achieve this. In JavaScript:
function findSequential(s) {
const res = []
let current = []
let num = 1
for(let char of s) {
if (char == num) {
current.push(char)
num ++
} else if (current.length > 1) {
res.push(current.reduce((acc, cur) => acc += cur, ''))
if (char == 1) {
current = ['1']
num = 2
} else {
current = []
num = 1
}
} else if (current.length === 1) {
current = []
num = 1
}
}
if (current.length > 1) {
res.push(current.reduce((acc, cur) => acc += cur, ''))
}
return res
}
console.log(findSequential('31234121'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With