タグを指定できるが、特定の単語しか含まれていない場合は、
別操作をしたいということでロジックで悩んだので、確認
対象の文字列を削除しても文字が残るかどうかを基準に判断。
const tag = '<ignore>■</ignore>'
const onlyReplacementText = [`${tag}`];
const onlyReplacementText2 =[`${tag}${tag}`];
const onlyReplacementText3 =[
`${tag}`,
`${tag}`
];
const withReplaceMeantText = [`${tag}を食べたいです。`];
const withReplaceMeantText2 = [`美味しい${tag}`];
const withReplaceMeantText3 =[
`${tag},${tag}`,
`${tag}`,
`${tag}`
];
const withReplaceMeantText4 =[
`${tag},${tag}があるみたいです。`,
];
const withReplaceMeantText5 =[
'こんにちは',
];
const ignoreTag = '<ignore>.</ignore>';
const hasTranslateText = (array) => {
const result = array.map(sentence => sentence.replace(/<ignore>.<\/ignore>/g, "")).filter(e => e !== '');
return result.length > 0
};
console.debug('1Expect false:',hasTranslateText(onlyReplacementText));
console.debug('2Expect false:',hasTranslateText(onlyReplacementText2));
console.debug('3Expect false:',hasTranslateText(onlyReplacementText3));
console.debug('1Expect true:',hasTranslateText(withReplaceMeantText));
console.debug('2Expect true:',hasTranslateText(withReplaceMeantText2));
console.debug('3Expect true:',hasTranslateText(withReplaceMeantText3));
console.debug('4Expect true:',hasTranslateText(withReplaceMeantText4));
console.debug('5Expect true:',hasTranslateText(withReplaceMeantText5));
追記
@947lj さんからより簡潔な下記の書き方を教えて頂きました。
ありがとうございます。
const hasTranslateText = (array) => {
return array.join('').replace(/<ignore>.<\/ignore>/g, '') !== '';
};
失敗談:
String.prototype.match()
を最初使おうとして失敗したのも記念に(?)残しておきます
// タグ+文章
const regex = new RegExp(`${ignoreTag}.`, 'g');
// 文章+タグ
const regex2 = new RegExp(`.${ignoreTag}`, 'g');
// タグ+タグ(タグの連続)
const regex3 = new RegExp(`${ignoreTag}${ignoreTag}`, 'g');
const hasTranslateText = (array) => {
let hasTranslateText = true;
for (const sentence of array) {
let isTag = false;
if (sentence.match(regex) || sentence.match(regex2)) {
isTag = false;
}
if (sentence.match(regex3)) {
isTag = true;
}
if (isTag === true) {
hasTranslateText = false;
}
}
return hasTranslateText;
};
にしても全くもって上手く行かなかったのですが、
戒めのために残しておきます。
もし、より良い方法がございましたら是非ともご提案いただければ幸です。