HTML字符串和iOS富文本转换

服务端返回的不一定都是纯字符串,有可能是带有HTML标签的
//html字符串转换为富文本

NSString *html = @"<p style='color:green'>首付<span style='color:#e83c36;'>5000元</span>,提前付<span style='color:red'>3倍月供</span>,月供<span style='color:red'>3000元</span>(48期)</p>";
NSAttributedString *attStr = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];

//富文本转换为html字符串

//富文本转换为html(最后相当于整个网页代码,会有css等)
NSDictionary *dic = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:@(NSUnicodeStringEncoding)};
NSData *data = [attStr dataFromRange:NSMakeRange(0, attStr.length) documentAttributes:dic error:nil];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 JavaScript 中,可以使用以下方法进行字符串文本转换: 1. 将字符串转换文本:使用 `JSON.stringify()` 方法将一个 JavaScript 对象或值转换为 JSON 格式的字符串。例如: ``` const obj = { name: "Alice", age: 23 }; const text = JSON.stringify(obj); console.log(text); // 输出结果为:{"name":"Alice","age":23} ``` 2. 将文本转换字符串:使用 `JSON.parse()` 方法将一个 JSON 格式的字符串转换为 JavaScript 对象或值。例如: ``` const text = '{"name":"Alice","age":23}'; const obj = JSON.parse(text); console.log(obj); // 输出结果为:{ name: "Alice", age: 23 } ``` 注意,使用 `JSON.stringify()` 方法转换对象时,对象中的函数和原型链上的属性都会被忽略掉。如果需要将对象中的函数和原型链上的属性也转换字符串,可以使用第三方库如 `Lodash` 的 `_.cloneDeepWith()` 方法。 例如,可以使用以下代码将一个对象及其原型链上的属性都转换字符串: ``` const _ = require('lodash'); class Person { constructor(name, age) { this.name = name; this.age = age; } sayHello() { console.log(`Hello, my name is ${this.name} and my age is ${this.age}.`); } } const alice = new Person("Alice", 23); const obj = _.cloneDeepWith(alice, (value) => { if (typeof value === 'function') { return value.toString(); } }); const text = JSON.stringify(obj); console.log(text); // 输出结果为:{"name":"Alice","age":23,"__proto__":{"constructor":"function Person(name, age) {\n this.name = name;\n this.age = age;\n}\n\nPerson.prototype.sayHello = function () {\n console.log(`Hello, my name is ${this.name} and my age is ${this.age}.`);\n}"}} ``` 其中,`_.cloneDeepWith()` 方法接收两个参数,第一个参数是需要进行深度克隆的对象,第二个参数是一个回调函数,在回调函数中可以自定义克隆的行为。在上面的例子中,回调函数判断如果当前值是函数,则将函数转换字符串返回。这样就可以将对象及其原型链上的属性都转换字符串了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值