将字符串编码为HTML字符串Swift 3 [英] Encode String to HTML String Swift 3

查看:62
本文介绍了将字符串编码为HTML字符串Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何快速编码字符串以删除所有特殊字符,并用匹配的html数字替换它.

How can I encode a string in swift to remove all special characters and replace it with its matching html number.

让我们说我有以下字符串:

Lets say I have the following String:

var mystring = "This is my String & That's it."

,然后将特殊字符替换为其html数字

and then replace the special characters with its html number

& = &
' = '
> = >

但是我想对所有特殊字符都执行此操作,而不仅仅是上面字符串中列出的那些特殊字符.怎么办?

But I want to do this for all Special Characters not just the ones listed in the string above. How would this be done?

推荐答案

extension String {
    func makeHTMLfriendly() -> String {
        var finalString = ""
        for char in self {
            for scalar in String(char).unicodeScalars {
                finalString.append("&#\(scalar.value)")
            }
        }
        return finalString
    }
}

用法:

newString = oldString.makeHTMLfriendly()

这似乎可以正常使用(尽管我不确定Unicode标量始终与HTML数字匹配).

This appears to work in general (although I don't know for sure that unicode scalars always match HTML numbers).

请注意,它会转换所有内容,甚至包括不需要真正转换的字母数字字符.编辑它以不进行某些转换可能并不难.

Note that it converts everything, even things like alphanumeric characters that don't really need to be converted. It probably wouldn't be too difficult to edit it to not convert some things.

这篇关于将字符串编码为HTML字符串Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆