javascript - 如何替换从 react-native 中的数组获得的字符串
问题描述
我需要用其他字符串替换字符串。我该如何更换?下面的代码仅更改 if 条件的第一条消息。我需要更改我需要的所有消息。
以下更改仅反映我的包里有书。”、“所有包里都有球”。其他如果不工作。(即)首先如果只有工作,其他人不工作。
代码:
renderMessages() {
if (message.length > 2) {
return (<Text>Available all sports items</Text>
} else {
return (
this.state.validation.messages.map((msg) => {
if (msg.indexOf('My bag contains books' > -1)) {
let messagess = msg.replace("My bag contains books.", "All the bag have balls")
return <Text style={{ fontSize: 13, color: 'red', marginBottom: 10, marginTop: 0 }}>{messagess}</Text>
}
if (msg.indexOf('My badminton bat' > -1)) {
let messagess = msg.replace("My badminton bat", "Our basket balls")
return <Text style={{ fontSize: 13, color: 'red', marginBottom: 10, marginTop: 0 }}>{messagess}</Text>
}
if (msg.indexOf('I have ball point pen' > -1)) {
let messagess = msg.replace("I have ball point pen", "My pencils are in my bag")
return <Text style={{ fontSize: 13, color: 'red', marginBottom: 10, marginTop: 0 }}>{messagess}</Text>
} else {
return (
<Text style={{ fontSize: 13, color: 'red', marginBottom: 10, marginTop: 0 }}>
{msg}
</Text>
}
})
)
}
}
解决方案
您的代码中有两个错误(如最初发布的那样):
括号在您的所有匹配条件中都放错了位置:
if (msg.indexOf('My bag contains books' > 0))
应该:
if (msg.indexOf('My bag contains books') > 0)
在这些相同的匹配条件下,您存在“一对一”的逻辑缺陷。它应该是
if (msg.indexOf('My bag contains books') > -1)
因为 Javascript 中的字符串索引,就像数组索引一样,从 0 开始。
-1
如果不匹配,则返回 String.indexOf。> 0
仅当您想忽略字符串开头的匹配项时才有意义。
推荐阅读
- javascript - 更改数组变量名称
- javascript - KaIOs - Kaiads 频率上限生效。kaios 广告未按时响应
- typescript - 如何正确定义包装 3rd 方类的代理的类型?
- python - 从列表中查找数据框中单词的频率
- c# - 如何预防/修复 - 外部服务交互 (DNS)
- html - 是否可以在未选中时将选项值设置为“false”以发送电子邮件?
- xml - 如何为 XML 文件编写 xPath
- r - 使用唯一 ID 合并两个数据帧而不重复
- python - 计算每小时 Python 熊猫的入住人数
- java - 通过 websockets 上的 amqp 从 kubernetes 集群内部连接到 azure iot hub