我有一个字符串,其中有一个标签</ p>,我想在</ p>之前附加</ b>
let str = "<p>A new week-long event is kicking off soon in <a href="/pokemon-go/" data-ref-id="5000-449545">Pokemon Go</a>. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.</p><p>During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.</p>"
Run Code Online (Sandbox Code Playgroud)
我希望此字符串为:
let newStr = #"<b><p>A new week-long event is kicking off soon in <a href="/pokemon-go/" data-ref-id="5000-449545">Pokemon Go</a>. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.</p></b><p>During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.</p>"#
Run Code Online (Sandbox Code Playgroud)
If you want to replace all occurrences of a string with another string you can use replacingOccurrences(of:with:). If you want to replace the first occurrence find range of the substring and replace with new substring
if let range = str.range(of: "<p>") {
str.replaceSubrange(range, with: "<b><p>")
}
if let range = str.range(of: "</p>") {
str.replaceSubrange(range, with: "</b></p>")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |