查找字符串并在末尾添加额外的
问题描述:
我有以下字符串。查找字符串并在末尾添加额外的
This is content
[divider space="123" anything="123"]
more content
[divider space="123"]
some more text or shortcodes
挑战是首先找到字符串[分隔符广告,然后在同一时间找到]一次]找到添加[/ divider]在最后。所以最终的输出将变为:
This is content
[divider space="123" anything="123"][/divider]
more content
[divider space="123"][/divider]
some more text or shortcodes
用下面的代码我可以找到字符串。
str = 'This is content[divider space="123" anything="123"][/divider]more content[divider space="123"][/divider] some more text or shortcodes';
str = str.match(divider(.*)]");
我怎么能找到第一个字符串,然后secondstring,之后添加一些[/除法。
答
可以使用replace
功能,并通过内部
$("p").html($("p").html().replace(/\[divider ([a-z]+\="\d+"\s?)+\]/g, s => s + "[/divider]"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
This is content
[divider space="123" anything="123"]
more content
[divider space="123"]
some more text or shortcodes
</p>
感谢理查德功能。看起来它会做的工作,但是你可以请检查我的小提琴不起作用https://jsfiddle.net/5opg7dq4/ – Themer
嗨@Richard汉密尔顿,我发现这个问题,它与正则表达式,第一个问题是如果例如,如果其变量名称包含大写字母,如果它的anyThing =“123”它不起作用,其次,如果任何属性为空例如任何东西=“”它再次停止工作,你能改变正则表达式,这里是小提琴:https://jsfiddle.net/5opg7dq4/4/ – Themer