[英]Run functions for all occurrences of content in string enclosed in square brackets
I have a string. 我有一个字符串。 The data is from a text area and contains occurrences of (varying) content enclosed in square brackets.
数据来自文本区域,并且包含出现在方括号中的(各种)内容。
I would like to run functions (eg replace) on the string content that is enclosed in square brackets, then update the original string to reflect the changes made. 我想在方括号内的字符串内容上运行函数(例如,replace),然后更新原始字符串以反映所做的更改。
Example 例
not this [potentially act on this token] not this [potentially act on this token] not this
I think some of the following may be involved but I can't figure out how to implement a working solution. 我认为可能涉及以下方面,但我不知道如何实施可行的解决方案。 I wouldn't like to use jQuery or external libraries.
我不想使用jQuery或外部库。
Here's a starting point JSFiddle . 这是JSFiddle的起点。
If anyone could be of any assistance, I'd really appreciate it. 如果有人可以提供任何帮助,我将非常感激。
Thank you very much. 非常感谢你。
Try something like this ... 尝试这样的事情...
var startEnd = user_input.match( /(\[.*?\])/g );
startend
is now an array of the bracketed values that you can now use for search/replace. startend
现在是一个带括号的值的数组,您现在可以将它们用于搜索/替换。
So your jsfiidle has pretty much all you need, except that the replace function can take a callback. 因此,您的jsfiidle几乎满足了您的所有需求,除了replace函数可以接受回调。 This callback receives one parameter which is the matched string and whatever you return is substituted for the match
此回调接收一个参数,它是匹配的字符串,并且您返回的任何内容都将替换为匹配项
user_input = user_input.replace(/\[.*\]/gi,function(match){
return match + "foo";
});
http://jsfiddle.net/fdtxvyo7/6/ http://jsfiddle.net/fdtxvyo7/6/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.