如果y包含x的最后一个单词,我想用y替换x的最后一个单词。我该如何处理?
let x ='jaguar lion tiger panda'
let y = 'pandas'
预期结果:
'jaguar lion tiger pandas'
如果
y = 'cat'
预期结果:
'jaguar lion tiger panda cat'
我尝试过的代码:
console.log(response)
let before = this.text.split(' ')
console.log(before)
console.log(before.length)
let a = before.slice(before.length-1)
console.log(a)
if (response.data.text[0].includes(a)) {
let x = (before.slice(0, before.length-1))
let y = x.replace(',', ' ')
this.preResult = y.push(response.data.text[0])
} else {
this.preResult.push(this.text + ' ' + response.data.text[0])
答案 0 :(得分:3)
您可以使用正则表达式匹配最后一个单词,然后通过检查单词y
includes
来进行测试。如果是这样,请用y
替换该单词,否则请替换为与y
串联的原始单词:
const x ='jaguar lion tiger panda'
const doReplace = y => x.replace(
/\S+$/, // match non-space characters, followed by the end of the string
(word) => (
y.includes(word)
? y
: word + ' ' + y
)
);
console.log(doReplace('pandas'));
console.log(doReplace('cat'));
答案 1 :(得分:0)
另一种解决方案:
let x ='jaguar lion tiger panda'
let y = 'pandas'
let splited = x.split(' ')
let lastWord = splited[splited.length - 1]
if(y.indexOf(lastWord) >= 0){
splited[splited.length - 1] = y
}else{
splited.push(y)
}
let result = splited.join(' ')
console.log(result)
答案 2 :(得分:0)
function replaceLastWord(x, y) {
let result = x.split(' '), lastIndex = (result.length || 1) - 1, lastWord = result[lastIndex]
result[lastIndex] = y.indexOf(lastWord) !== -1 ? y : `${lastWord} ${y}`
return result.join(' ')
}
console.log(replaceLastWord('jaguar lion tiger panda', 'pandas'))
console.log(replaceLastWord('jaguar lion tiger panda', 'cat'))
console.log(replaceLastWord('', 'pandas'))