0

Let's say I have a string that starts by 7878 and ends by 0d0a or 0D0A such as:

var string = "78780d0101234567890123450016efe20d0a";
var string2 = "78780d0101234567890123450016efe20d0a78780d0103588990504943870016efe20d0a";
var string 3 = "78780d0101234567890123450016efe20d0a78780d0103588990504943870016efe20d0a78780d0101234567890123450016efe20d0a"

How can I split it by regex so it becomes an array like:

['78780d0101234567890123450016efe20d0a']
['78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a']
['78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a']
2
  • I wouldn't use regex, I would use length; it looks like they are always the same length? Commented Jun 9, 2015 at 14:56
  • Im sorry, bad example. They are not always the same length Commented Jun 9, 2015 at 14:57

1 Answer 1

2

You can split the string with a positive lookahead (?=7878). The regex isn't consuming any characters, so 7878 will be part of the string.

var rgx = /(?=7878)/;
console.log(string1.split(rgx));
console.log(string2.split(rgx));
console.log(string3.split(rgx));

Another option is to split on '7878' and then take all the elements except first and add '7878' to each of them. For example:

var arr = string3.split('7878').slice(1).map(function(str){
    return '7878' + str;
});

That works BUT it also matches strings that do NOT end on 0d0a. How can I only matches those ending on 0d0a OR 0D0A?

Well, then you can use String.match with a plain regex.

console.log(string3.match(/7878.*?0d0a/ig));
Sign up to request clarification or add additional context in comments.

2 Comments

That works BUT it also matches strings that do NOT end on 0d0a. How can I only matches those ending on 0d0a OR 0D0A?
Works! Supposing all characters in the string are hex, can I use this regex as well? /7878[a-f0-9]+?0d0a/ig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.