我有以下功能,但我的字符串永远不会被替换?我做错了什么?
function customRegex(){
return function(myString,replacement,myValue){
var s = myString;
var rgx = new RegExp("/("+replacement+")/,gi");
myString = myString.replace(rgx, myValue);
return myString;
}
}
var reg = customRegex();
console.log( reg("This is the worst!","worst","best"));
//This is always returning the original string?
答案 0 :(得分:1)
正则表达式声明存在问题。您似乎尝试添加正则表达式分隔符,但[...]
$content = new \SendGrid\Content('text/plain', 'Hi -name-, lorem ipsum');
$mail->addContent($content);
foreach ($recipients as $recipient) {
$personalization = new \SendGrid\Personalization();
$email = new \SendGrid\Email(null, $recipient['email']);
$personalization->addTo($email);
$personalization->addSubstitution('-name-', $recipient['name']);
$mail->addPersonalization($personalization);
}
$response = $sg->client->mail()->send()->post($mail);
构造函数在构建动态模式时接受字符串,因此,RegExp
在字符串模式中被视为文字符号。正则表达式修饰符/
应该作为第二个字符串参数传递。
使用
gi
请参阅下面的演示:
var rgx = new RegExp(replacement,"gi");
此外,如果您的搜索模式可以包含特殊的正则表达式元字符,则需要将它们转义。见Is there a RegExp.escape function in Javascript? SO帖子。