简体   繁体   English

JavaScript 获取所有字符实例之间的所有子串

[英]JavaScript Get all substrings between all instances of characters

I have a string with HTML code:我有一个带有HTML代码的字符串:

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

I want to change all the substrings between < and > to a div element.我想将<>之间的所有子字符串更改为div元素。 Here is the desired result:这是期望的结果:

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

Sort of like .replace() , except the inside of the <> could be anything.有点像.replace() ,除了<>的内部可以是任何东西。

Please avoid Regex if possible.如果可能,请避免使用正则表达式。 Thanks!谢谢!

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. /<(\/?)\w+>/g是第一个来找我的。

Parsing html with regex is not a good idea , but in this case it seems fine for a known set of inputs.用正则表达式解析 html 不是一个好主意,但在这种情况下,对于一组已知的输入来说似乎没问题。

Replace can be used with regex to target any string that matches a pattern, and replace part of it with something else. Replace 可以与正则表达式一起使用来定位与模式匹配的任何字符串,并将其中的一部分替换为其他内容。

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.如果您不想使用正则表达式,您可以逐个字符地解析字符串,但这会执行得很差,而且更复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM