split string at ">" only if the next charakter equals "<" keep the charakters in javascript

You can use a regular expression with lookahead to match the > character only if it is followed by a < character. Then you can call the split method on your string and pass in the regular expression as the separator parameter. This will split the string at the > character only if it is followed by a < character:

index.tsx
let str = "hello>world<how>are<you";
let regex = />(?=<)/g;
let splitArr = str.split(regex);

console.log(splitArr); // ["hello", "world<how", "are", "you"]
157 chars
6 lines

In this example, the regular expression /(?=<)/g matches the > character only if it is followed by a < character. The g flag is used to perform a global search, so all occurrences of the regex in the string are matched.

The splitArr variable contains the result of calling the split method on the str variable using the regex variable as the separator. The resulting array contains the substrings from the str variable split at the > character only if it is followed by a < character.

related categories

gistlibby LogSnag