Split a string based on multiple delimiters [/, #, @, '']

I want to split a string based on multiple delimiters.

How to split a line with multiple lines as a separator?

For example:

I have a line: "/create #channel 'name' 'description of the channel' #field1 #field2"

And I want an array with:

/create
#channel
name
description of the channel
#field1
#field2

Another example: "/send @user 'A messsage'" And I want:

/send
@user
A message

How to solve it? Any help please ?: - (

+4
source share
5 answers

You can use regex

/([\/#]\w+|'[\s\w]+')/g

For clarification regex: https://regex101.com/r/lE4rJ7/3

  • [\/#@]\w+: This will match lines starting with #, /or@
  • |: OR condition
  • '[\s\w]+': matches quoted strings

, .

var regex = /([\/#@]\w+|'[\s\w]+')/g;

function splitString(str) {
  return str.match(regex).join().replace(/'/g, '').split(',');
}

var str1 = "/create #channel 'name' 'description of the channel' #field1 #field2 @Tushar";
var str2 = "/send @user 'A messsage'";

var res1 = splitString(str1);
var res2 = splitString(str2);

console.log(res1);
console.log(res2);

document.write(res1);
document.write('<br /><br />' + res2);
Hide result
+1

Regx

var multiSplit = function (str, delimeters) {
    var result = [str];
    if (typeof (delimeters) == 'string')
        delimeters = [delimeters];
    while (delimeters.length > 0) {
        for (var i = 0; i < result.length; i++) {
            var tempSplit = result[i].split(delimeters[0]);
            result = result.slice(0, i).concat(tempSplit).concat(result.slice(i + 1));
        }
        delimeters.shift();
    }
    return result;
}

multiSplit("/create #channel 'name' 'description of the channel' #field1 #field2",['/','#','@',"'"])

Array [ "", "create ", "channel ", "name", " ", "description of the channel", " ", "field1 ", "field2" ]
+2

, split:

('[^']+'|[^\s']+)

: !

: http://jsfiddle.net/k8s8r77e/1/

, . , .

0

- ... ,

var w = "/create #channel 'name' 'description of the channel' #field1 #field2";

var ar = w.split();

ar.forEach(function(e, i){  
    e = e.replace(/'/g, '')
    console.log(e)
})

: http://jsfiddle.net/d9m9o6ao/

0

, , - , , , , , . , "", " ", #channel - #. 2 :

String.split , :

var re = /['\/@#"]+\s*['\/@#"]*/;

var str = "/create #channel 'name' 'description of the channel' #field1 #field2";
var parts = str.split(re);

. : , .

, string.match regexp:

var re = /['\/@#"][^'\/@#"]*/g;
var parts = str.match(re);
0

Source: https://habr.com/ru/post/1608764/


All Articles