如何查找后跟空格的单词并替换为标签

How to find words followed by space and replace with tag?

本文关键字:单词 替换 标签 空格 何查找 查找      更新时间:2023-09-26

>数组中有一些字符串值

var anchors = [
        "Can", 
        ", please?"
    ];

我有类似以下示例的字符串

<anchor>0</anchor> you repeat that<anchor>1</anchor>

我想在下面框住生成的字符串

Can <drop></drop> <drop></drop> <drop></drop>, please?
I want to replace all the <anchor>0</anchor> to the words in the given array and words into <drop></drop> tag

有人请帮我使用 javascript 字符串操作或正则表达式构建生成的字符串

你可以尝试如下

var myarray =[ "Can",",please?" ];
var inputstring ="<anchor>0</anchor> you repeat that <anchor>1</anchor>"
var len=inputstring.split(" ").length-1
var inputstring1;
for(var i=0;i<=myarray.length;i++)
{
inputstring1 +=   inputstring.replace("<anchor>"+i+"</anchor>",myarray[i]) 
}
var inputstring2=inputstring
for(var i=0;i<=myarray.length;i++)
{
inputstring2 =   inputstring2.replace("<anchor>"+i+"</anchor>","") 
}
myarrayremovedelemets=inputstring2.split(" ")
myarrayremovedelemets.push.apply(myarrayremovedelemets, myarray);
alert(myarrayremovedelemets);

然后将输入字符串 1 替换为 <drop></drop>

您可以将以下逻辑与callback function一起使用:

输出:

Can <drop></drop> <drop></drop> <drop></drop>, please?

法典:

var anchors = [
    "Can", 
    ", please?"
];
var replaceCallback = function(match, g1, g2) { 
if(g1 != null) return anchors[g1];
if(g2 != null) return "<drop></drop>";
return match;
}
var str = "<anchor>0</anchor> you repeat that<anchor>1</anchor>";
str = str.replace(/<anchor>('d+)<'/anchor>|('w+)/g, replaceCallback); 
alert(str);

编辑:更新的正则表达式:

/<anchor>('d+)<'/anchor>|((?:(?!<anchor>)'S)+)/g

编辑:对于single

/<(?:anchor|single)>('d+)<'/(?:anchor|single)>|((?:(?!<(?:anchor|single)>)'S)+)/g