Javascript-替换字符串子字符串中的字符
我有一个这样的字符串/是abc/def/fgh/uio的一个示例 我想把最长的单词作为目标,并用a+替换这个子字符串上的any/ 我设法识别出最长的单词,我知道如何用a+替换所有/但我不知道如何替换最长单词中的/ 这是我到目前为止得到的Javascript-替换字符串子字符串中的字符,javascript,regex,Javascript,Regex,我有一个这样的字符串/是abc/def/fgh/uio的一个示例 我想把最长的单词作为目标,并用a+替换这个子字符串上的any/ 我设法识别出最长的单词,我知道如何用a+替换所有/但我不知道如何替换最长单词中的/ 这是我到目前为止得到的 //identify longest word in string function longestWord(str) { var words = str.split(' '); return words.reduce(longer); } functi
//identify longest word in string
function longestWord(str) {
var words = str.split(' ');
return words.reduce(longer);
}
function longer(champ, contender) {
return (contender.length > champ.length) ? contender: champ;
}
//purely given an exemple, some strigns won't be exactly like this
var text2 = "this/ is an example abc/def/fgh/uio to give you an example"
if (longestWord(text2) > 30 ) {
text2.replace(/\//g, ' / ');
}
问题是,这也将替换子字符串this/上的/,我不希望这样
如何实现这一点?您的longestWord函数返回字符串中最长的单词,因此您可以将该字符串单独传递,而不是将正则表达式作为第一个参数传递给。替换,并将对该最长单词调用的//\//g替换为第二个参数:
函数getLongestWordstr{
var words=str.split';
返回words.reducelonger;
}
功能longerchamp,竞争者{
返回竞争者.length>champ.length?竞争者:champ;
}
var text2=这是一个示例abc/def/fgh/uio,为您提供了一个示例
const longestWord=getLongestWordtext2;
const output=text2.replacelongestWord,longestWord.replace/\//g,“+”;
console.logoutput @CertainPermance的解决方案要优雅得多,我认为它比这更有效,但在我写下答案时,我想我还是把它放进去吧 事实上,这是相当相似的,虽然在这个例子中,我们得到了单词的索引,并使用它来执行替换,在撰写本文时,我认为这是必要的。现在看看更好的解决方案,我意识到这样的检查是不必要的,因为字符串中最长的单词在任何其他单词中都不会出现,所以简单地对其执行替换操作既简单又安全 const data=this/是abc/def/fgh/uio的一个示例,为您提供一个示例; const getLongestWordIndex=stringIn=>stringIn .拆分“ 减少 上一个,当前,i=>curr.length>prev.length?{ 索引:i,, 长度:当前长度 }:上, { 长度:-1, 索引:-1 } 指数 const replaceLongestWord=句子,replacer=>{ const longestWordIndex=getlongestwordindexcentence; const words=data.split“”; 返回Object.values{ …语言, [longestWordIndex]:替换词[longestWordIndex] }.加入“ } const-wordReplaceFunction=word=>word.replace/\//g,'+' const result=replaceLongestWorddata,wordReplaceFunction;
console.dirresultSplit,查找最长单词,替换,concat back。然后你可以将你的正则表达式更新为/\/?=\S/你没有使用longestworder返回的单词。我以前从未在reduce方法中使用过变量名“竞争者”和“冠军”,我可能不得不采用它!谢谢你的评论,很有趣!