写js代码,使用正则表达式,遍历多行文本,如果一行文本中出现(size:70%),那么删除(size:70%),并用<span style="font-size:70%"><span>包裹这行文本,如果出现(size:80%),那么删除(size:80%),并用<span style="font-size:80%"><span>包裹这行文本。注意数值的变化
时间: 2024-03-21 15:44:04 浏览: 48
Java中使用正则表达式处理文本数据
5星 · 资源好评率100%
好的,以下是一个使用 JavaScript 正则表达式的示例代码:
```javascript
const text = `
This is a sample text with (size:70%) some text in size 70
and (size:80%) some in size 80.
We need to wrap the text in <span> tags based on the size.
`;
// Regular expression to match (size:xx%)
const sizeRegex = /\(size:(\d+)%\)/g;
// Split the text into lines
const lines = text.split("\n");
// Loop through each line of text
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Find any matches for (size:xx%)
const matches = line.match(sizeRegex);
if (matches) {
for (let j = 0; j < matches.length; j++) {
const match = matches[j];
const fontSize = match.match(/\d+/)[0];
// Remove (size:xx%) from the line
const updatedLine = line.replace(match, "");
// Wrap the line in <span> tags with the appropriate font size
const spanTag = `<span style="font-size:${fontSize}%">${updatedLine}</span>`;
// Replace the line with the updated line
lines[i] = spanTag;
}
}
}
// Join the lines back together
const updatedText = lines.join("\n");
console.log(updatedText);
```
这个代码会遍历输入的多行文本,并查找每行中出现的`(size:xx%)`字符串。如果找到了,则会从该行中删除`(size:xx%)`字符串,并使用`<span>`标签包裹该行文本,并设置正确的字体大小。最后,输出更新后的文本。
阅读全文