Home > Net >  JavaScript Get all substrings between all instances of characters
JavaScript Get all substrings between all instances of characters

Time:09-26

I have a string with HTML code:

let string = '<span><p>Hello</p></span>';

I want to change all the substrings between < and > to a div element. Here is the desired result:

let desired = '<div><div>Hello</div></div>';

Sort of like .replace(), except the inside of the <> could be anything.

Please avoid Regex if possible. Thanks!

CodePudding user response:

You asked for a non regex solution, but this is a perfect application of regex. /<(\/?)\w >/g is the first one to come to me.

Parsing html with regex is not a good idea, but in this case it seems fine for a known set of inputs.

Replace can be used with regex to target any string that matches a pattern, and replace part of it with something else.

Here is a code example using the above regex:

const regex = /<(\/?)\w >/g
const subst = `<$1div>`

const tagToDiv = (str) => str.replace(regex, subst)

const str1 = `<span><p>Hello</p></span>`
const str2 = `regex should not parse html <yes> <no>`

console.log({str1, result: tagToDiv(str1)})
console.log({str2, result: tagToDiv(str2)})

If you don't want to use regex, you can parse the string character by character, but this will perform badly, with more complexity.

  • Related