function findall(a, x) {
//a:数组,x:数组中的元素
var results = [],
len = a.length,
pos = 0
while (pos < len) {
pos = a.indexOf(x, pos)
if (pos === -1) {
//未找到就退出循环完成搜索
break
}
results.push(pos) //找到就存储索引
pos += 1 //并从下个位置开始搜索
}
return results
}
一个应用:这里是将content中的[text]
替换为input
输入框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body></body>
<script>
// 注意[Text]可能有,可能没有
let x = '1、没有车牌,扣[Text]'
let y = x.split('')
//y.join("")
// y.toString("")
//在数组a中查找所有出现的x,并返回一个包含匹配索引的数组
function findall(a, x) {
//a:数组,x:数组中的元素
var results = [],
len = a.length,
pos = 0
while (pos < len) {
pos = a.indexOf(x, pos)
if (pos === -1) {
//未找到就退出循环完成搜索
break
}
results.push(pos) //找到就存储索引
pos += 1 //并从下个位置开始搜索
}
return results
}
//
var l = findall(y, '[')
// l:[10, 34, 51, 75]
let mes = {}
l.forEach(function(val, index, arr) {
if (arr.length > 1) {
if (index == 0) {
//第一个
mes[index] = x.substring(0, val)
} else if (index == arr.length - 1) {
//最后一个
mes[index] = x.substring(arr[index - 1] + 6, val)
// let finallyIndex = arr[index-1]
mes[index + 1] = x.substring(val + 6, y.length)
} else {
mes[index] = x.substring(arr[index - 1] + 6, val)
}
}else{
mes[index] = x.substring(0, val)
mes[index + 1] = x.substring(val + 6, y.length)
}
})
console.log(mes)
let str = ''
for (let x in mes) {
str += mes[x] + '<input>'
}
console.log(str)
</script>
</html>