从JavaScript中的列表keyCode拆分字符串

时间:2018-10-26 03:27:48

标签: javascript

我有一个代表分隔符的keyCode列表。用户输入一个字符串(从文本框输入)后,如何用keyCode列表拆分该字符串?到目前为止,split()函数允许使用字符串或regexp,但在将keyCode转换为regexp时我什么也没发现。

在这种情况下我该怎么办?

例如:

separators = [ 
    mdConstants.KEY_CODE.COMMA // 188
    mdConstants.KEY_CODE.DASH: // 189
    ...
]

Input -> Output
------------------
abc-def -> [ abc, def ]
abc-def.efg -> [ abc, def, efg ]

5 个答案:

答案 0 :(得分:2)

您可以在拆分中使用正则表达式:

// eg ,-
var separators = [44, 45];
var myText = "this, is a - test";

var regex = "[" + separators.map(function (c) { return String.fromCharCode(c); }).join("") + "]"; 

var groupedItems = myText.split(new RegExp(regex));
console.log(groupedItems);

答案 1 :(得分:1)

不确定是否是您想要的,但是根据我对您问题的理解,这是一个存根:

sed 's/^.\{,5\}//' file.dat

答案 2 :(得分:1)

可以使用RegExp对象分割字符串。

//assuming an object is given
const mdConstants = {
  "KEY_CODE": {
    "COMMA": ",",
    "DASH": "-",
    "DOT": "."
  }
};

//you can create separator list

const separators = Object.keys(mdConstants.KEY_CODE).map(k => '[' + mdConstants.KEY_CODE[k] + ']'); //sanitize symbols to avoid RegExp special character conflicts

//create RegExp object
const re = new RegExp(separators.join('|'));

//and use it

console.log('abc-def.ghi,jkl'.split(re));

答案 3 :(得分:0)

您可以在输入框中监听onKeyDown事件,这将为您提供一个事件对象。您的函数可能看起来像这样。

var tempWord = ""; var arrayYouWant = []; var separators = [];

function onKeyDownHandler (event) {
    var value = event.target.value;
    var keyCode = event.which || event.keyCode;
    if (separators.indexOf(keyCode) === -1) {
        tempWord += value;
    } else {
        arrayYouWant.push(tempWord);
        tempWord = "";
    }
}

这是一个模糊的实现,但是希望您能理解。

答案 4 :(得分:0)

您可以尝试用第一个分隔符替换所有分隔符,然后使用javascript的split函数和第一个分隔符进行拆分。

这里是一个例子:

/usr/lib/qt5/bin/lrelease qtterminal/po/qtgnuplot_fr.ts -qm qtgnuplot_fr.qm
/bin/bash: /usr/lib/qt5/bin/lrelease: No such file or directory
Makefile:1335: recipe for target 'qtgnuplot_fr.qm' failed
make[4]: *** [qtgnuplot_fr.qm] Error 127
make[4]: Leaving directory '/home/seolhwa/Downloads/gnuplot-5.0.7/src'
Makefile:1027: recipe for target 'all-recursive' failed
make[3]: *** [all-recursive] Error 1
make[3]: Leaving directory '/home/seolhwa/Downloads/gnuplot-5.0.7/src'
Makefile:644: recipe for target 'all' failed
make[2]: *** [all] Error 2
make[2]: Leaving directory '/home/seolhwa/Downloads/gnuplot-5.0.7/src'
Makefile:419: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/seolhwa/Downloads/gnuplot-5.0.7'
Makefile:357: recipe for target 'all' failed
make: *** [all] Error 2