我有一个文本,它是表达式公式,例如
add(1,2)+sin(90)+1/2+add_days(now(),30)+data
像 add(),sin(),add_days(),now()
有什么方法可以使用javascript中的正则表达式来标识函数,并用span标记替换以应用于样式。
需要最后的文字:
<span> add (</span>1,2<span>)</span>+<span>sin(</span>90<span>)</span>+1/2+<span>add_days(</span><span>now(</span><span>)</span>,30<span>)</span>+data
答案 0 :(得分:0)
var input = "add (1,2)+sin(90)+1/2+add_days(now(),30)";
var output = "<span> add </span> (1,2)+<span>sin</span>(90)+1/2+<span>add_days</span>(<span>now</span>(),30)";
var out = input.replace(/(\s?[a-z_]+\s?)/ig, "<span>$1</span>");
console.log(input);
console.log(output);
console.log(out);
/*
Output:
add (1,2)+sin(90)+1/2+add_days(now(),30)
<span> add </span> (1,2)+<span>sin</span>(90)+1/2+<span>add_days</span>(<span>now</span>(),30)
<span>add </span>(1,2)+<span>sin</span>(90)+1/2+<span>add_days</span>(<span>now</span>(),30)
*/
答案 1 :(得分:0)
如果您可以列出文档中使用的所有数学函数,则可能对您有用。
var MATH_FUNCTIONS = ['add', 'sin', 'add_days', 'now'];
var input = 'add(1,2)+sin(90)+1/2+add_days(now(),30)';
var regex = new RegExp('(\\b'+MATH_FUNCTIONS.join('\\b|')+'\\b)', 'gm');
input.replace(regex, '<span>$1</span>');
答案 2 :(得分:0)
使用$&替换即可解决问题。 $&有助于在多个组的情况下获得匹配的字符。
var input = "add (1,2)+sin(90)+1/2+add_days(now(),30)+data";
var out = input.replace(/(?:(\s?[a-z_]+\s?\()|(\)))/ig, "<span>$&</span>");
console.log(out);
//<span>add (</span>1,2<span>)</span>+<span>sin(</span>90<span>)</span>+1/2+<span>add_days(</span><span>now(</span><span>)</span>,30<span>)</span>+data