我想搜索字符串标题值,这些值将始终具有尾随破折号或管道以及末尾的特定变量,例如:">爱是真实的吗?- 示例">,或"在工作中不偷懒的十大方法 |再举个例子">
我的最终目标是,如果任何正则表达式匹配在字符串中返回正值(必须提供 exampleVariable(,则简单地调用替换函数,并将其完全从管道或破折号中删除并包含管道或破折号,如下所示:
brandNameTitle.replace((|)?(-)?s`${exampleVariable}`, '');
最终的结果是,爱情是真的吗?或者《在工作中不偷懒的十大方法
》 我知道我的正则表达式目前是错误的,并且我已经尝试了不同正则表达式的其他变体,但我的语法是错误的。任何帮助将不胜感激!
您可以使用此正则表达式进行搜索:
`\s*[|-]\s*${exampleVariable}$`
注意在正则表达式字符串中使用双斜杠。
法典:
function replTitle(brandNameTitle, exampleVariable) {
let re = new RegExp(`\s*[|-]\s*` + exampleVariable.replace(/.com$/, ""));
return brandNameTitle.replace(re, "");
}
console.log(replTitle(`Is love real? - Example`, `Example.com`))
console.log(replTitle(`Top 10 Ways To Not Be Lazy at Work | Another Example`,
`Another Example`))