繁体   English   中英

JavaScript-检查给定的子字符串是否被字母包围

[英]JavaScript - check if a given substring is surrounded by letters

TL; DR

我如何返回包含子字符串的字符串,但前提是不被字母包围?

语境

我正在创建一种虚构语言的翻译工具。 我有一个存储在JSON对象中的词典,并且正在使用以下代码将输入中的每个单词转换为输出中的另一个单词:

    //loop through lexicon and if inputted word is in values, return corresponding key -> NEED A WAY TO GET 
    for(var word in inputArray){    
        for(var key in lexicon){
            var value = lexicon[key];
            var term = inputArray[word];

            // check if the term appears as a value in the selected lexicon
            if(value.indexOf(term) !== -1){
                // if key contains commas, then take only what's before the first comma
                if(key.indexOf(',') !== -1){
                    match = key.substring(0, key.indexOf(','));
                // if there are no commas, return the whole key
                } else{
                    match = key;
                }
                outputArray.push(match)
                break;
            }
        }
    }

问题

尽管此方法适用于较长的单词,但较短的单词(例如“ hi ”)将与词典中找到的第一个值匹配,后者可能是另一个单词,例如“ t hi ng”。 由于某些对象值包含用逗号分隔的单词,因此我需要一种方法来仅提取不被字母包围的单词。

期望的结果

如果输入“ hi ”,将不返回“ thing ”的翻译,但将返回“ hi,hello,goodday ”或“ hello,hi ”的翻译。

您要匹配字符串中的整个单词吗? 您可以为此使用正则表达式:

new RegExp("\\b" + lookup + "\\b").test(text)

详情请参阅这里: javascript中的整个单词匹配

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM