Split string from a list keyCode in javascript

Viewed 517

I have a list of keyCode which stand for separator keys. After user inputs a string (from a textbox), how can I split that string by a list of keyCode? So far split() function is allowed string or regexp, I found nothing when converting keyCode to regexp.

What should I do in this case?

For example:

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

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

You can use regular expressions in split:

// 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);

Not completely sure if that's what you want, but here is a stub at it with my understanding of your question:

const separators = [ 
    ",",
    "-",
    "."
];

// make regex pattern from your separators.
// pipe serves as a char separator
// double is backslash for escaping chars
let pattern = new RegExp('\\' + separators.join('|\\'), "g");

// user input
let userInput = "abc-def.efg";

// resulting array of words split by your separators
let result = userInput.split(pattern);

console.log(result);

It is OK to use RegExp object to split a string.

//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));

You can listen for onKeyDown event on the input box, this will give you an event object. Your function can look something like this.

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 = "";
    }
}

This is a vague implementation, but I hope you get the idea.

You could try replacing all separators with the first separator and then do the split using javascript's split function and the first separator.

Here is an example:

var a = 'abc-def.efg';

for (var i = 0; i<separators.length; i++){
    a = a.replace(separators[i],separators[0]);
} 

var a_split = a.split(separators[0]);

console.log(a_split);
Related