[英]Replace a string with another string in some conditions
如果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])
您可以使用正則表達式匹配最后一個單詞,然后通過檢查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'));
另一個解決方案:
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)
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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.