0

I would like to parse the following string into a javascript array. Is Regex capable of performing such a task? How should I go about achieving this? I would like for the content to be capable of being dynamic other than the keys

<type1> <type2>

will remain the same. Meaning any combination of the string with any text should not matter. The keys are the delimiters.

Hello, I am your <type1> and <type2>!

array[0] = Hello, I am your
array[1] = <type1>
array[2] = and 
array[3] = <type2>
array[4] = !
0

2 Answers 2

1

I am not sure whether you are looking to do this with HTML context since you have tagged the question, if so, I would not do this and look for a better way such as using a parser.

You could split on preceding whitespace and the delimiters like this.

var r = 'Hello, I am your <type1> and <type2>!'.split(/\s*(<[^>]*>)\s*/);
console.log(r); //=> [ 'Hello, I am your', '<type1>', 'and', '<type2>', '!' ]

If you want to keep the preceding whitespace and only split on the delimiters.

var r = 'Hello, I am your <type1> and <type2>!'.split(/(<[^>]*>)/);
console.log(r); //=> [ 'Hello, I am your ', '<type1>', ' and ', '<type2>', '!' ]
Sign up to request clarification or add additional context in comments.

1 Comment

Will this Regex work with multiple languages given the <type1> key remains the same? Ie Chinese etc?
1

Assuming you're not trying to parse HTML with JavaScript:

str.split(/(<[^>]+>)/)

It splits the strings based on things between angular brackets.

Result

["Hello, I am your ", "<type1>", " and ", "<type2>", "!"]

1 Comment

Thank you very much. String will be extremely dynamic but not html. I am only using the tags to denote where I would like to insert a component . i.e Hello, I am your [button] and [image].

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.