split string between "><" but keep the charakters in javascript

You can split the string using a regular expression and then join the resulting array with the characters you split on. Here is an example code snippet:

index.tsx
const str = '<div>hello</div><span>world</span>';
const parts = str.split(/(?<=>)(?=<)/); // split on "><"
const result = parts.join('><'); // keep "><" between the parts
console.log(result); // output: <div>hello</div><span>world</span>
238 chars
5 lines

Here, we split the str variable on the regex /(?<=>)(?=<)/, which matches a point between > and < without including them in the match. This gives us an array of parts that we want to keep. We then join the parts using >< as the separator and store the result in result. Finally, we print out the result to the console.

Note that the /(?<=>)(?=<)/ regular expression uses lookbehind and lookahead assertions, which are a more advanced feature of regular expressions that may not be supported in older browsers. If you need to support older browsers, you can use a simpler regex like /></ and then trim the leading > and trailing < from each part.

related categories

gistlibby LogSnag