javascript - 替换()正则表达式多个换行符字符串不起作用javascript
问题描述
我有下一个字符串 bbcode 类型[MSG]abc[/MSG]
,我想用一个友好的字符串替换它......使用正则表达式
当 bbcode 仅在第一行时,我的代码有效,但是当我在[MSG]
带有换行符的标签中放置更多文本时......它不起作用......
做错了什么?
编码尝试
$("button").on("click", function(){
var textarea = $("#textarea").val();
var regex = /\[MSG\](.*)\[\/MSG]/ig;
textarea = textarea.replace(regex,"converted: $1 --");
$("div").text(textarea)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
hello [MSG]abc[/MSG]
<HR>
hello [MSG]a <BR>
bc[/MSG]
<HR>
<textarea id='textarea' rows=3>
hello [MSG]abc[/MSG]
/
hello [MSG]a
bc[/MSG]
</textarea>
<button>convert</button>
<div></div>
解决方案
您应该使用添加了 s 开关的单行模式正则表达式:
正则表达式 = /[MSG](.*?)[/MSG]/igs;
在正则表达式中,点匹配除换行符 \n 之外的每个字符。使用单行开关,所有换行符都集成到一个字符串中。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
hello [MSG]abc[/MSG]
<HR>
hello [MSG]a <BR>
bc[/MSG]
<HR>
<textarea id='textarea' rows=3>
hello [MSG]abc[/MSG]
/
hello [MSG]a
bc[/MSG]
</textarea>
<button>convert</button>
<div></div>
<script>
$("button").on("click", function(){
var textarea = $("#textarea").val();
var regex = /\[MSG\](.*?)\[\/MSG]/igs;
textarea = textarea.replace(regex, "converted: $1 --");
$("div").text(textarea)
})
</script>
本文可能是阅读https://www.regular-expressions.info/dot.html的良好开端
$("button").on("click", function(){
var textarea = $("#textarea").val();
var regex = /\[MSG\](.*?)\[\/MSG]/igs;
textarea = textarea.replace(regex, "converted: $1 --");
$("div").text(textarea)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
hello [MSG]abc[/MSG]
<HR>
hello [MSG]a <BR>
bc[/MSG]
<HR>
<textarea id='textarea' rows=3>
hello [MSG]abc[/MSG]
/
hello [MSG]a
bc[/MSG]
</textarea>
<button>convert</button>
<div></div>
推荐阅读
- python - __init__() 接受 1 个位置参数,但在一个非常简单的表单函数上给出了 2 个错误
- excel - 如何从 Excel 数据填充用户表单中的组合框下拉列表?
- file - .nii 扩展名的文件有分隔符吗?
- mysql - 此查询也显示昨天和今天的数据,但我只想要今天的数据
- jquery - 嵌套 $(document).ready() 以测试嵌套页面是否处于活动状态
- c# - Autofac 无法解析我的注册通用服务
- hashicorp-vault - HarshiCorpe Vault:收集的数据库凭据已过期,这种情况下的最佳做法是什么?
- c# - 使用实体框架异步填充 GridView
- php - strip_tags + html 实体仅获取数字
- c - C:所有字符串文字都有静态存储持续时间吗?