正在从Javascript中的字符串中删除短语



(function() {
function takeRecordingAway() {
try {
let $title = document.querySelector('.progTitle');
let splitInfo = $title.textContent.split(' ');
let lastInd = splitInfo.lastIndexOf('Recording');
let filterResult = splitInfo.slice(lastInd, splitInfo.length).join('');
let finalResult = splitInfo.join('').replace(filterResult, '');
$title.textContent = finalResult;
} catch(e) {
console.log("Error", e);
}

}

function init() {
takeRecordingAway();
}
init();
})();
<div class="progTitle">Advisory Round: Key Steps for StartupsRecording is not available for this program</div>

我正试图从字符串中删除一个短语。我想删除的短语是"录制不可用于此程序",来自以下字符串:

"咨询回合:启动记录的关键步骤不适用于此程序">

我怎样才能找到这个短语并将其删除?

目前我使用的这个功能并不完全有效:

(function() {
function takeRecordingAway() {
try {
let $title = document.querySelector('.progTitle'); //div containing the phrase
let splitInfo = $title.textContent.split(' ');
let lastInd = splitInfo.lastIndexOf('Recording');
let filterResult = splitInfo.slice(lastInd, splitInfo.length).join('');
let finalResult = splitInfo.join('').replace(filterResult, '');
$title.textContent = finalResult;
} catch(e) {
console.log("Error", e);
}

}
function init() {
takeRecordingAway();
}
init();
})();

使用String.prototype.replace()将标题的textContent替换为已过滤的textContent值即可。

function removePhraseFromTitle(phraseToFind) {
const title = document.querySelector('.progTitle');
title.textContent = title.textContent.replace(phraseToFind, '');
}
removePhraseFromTitle('Recording is not available for this program');
<div class="progTitle">Advisory Round: Key Steps for StartupsRecording is not available for this program</div>

在这个场景中,我会使用一个正则表达式来捕获上述短语。然后使用String.prototype.replace()将其移除。

function removePhrase(str) {
const re = /(Recording is not available for this program)/g;
return re.replace(re, '');
}

最新更新