Milad Ashrafi Milad Ashrafi - 3 years ago 93
Javascript Question

javaScript - splitting string in array that matches pattern

I have got for following string as an example

hello {{salutation}} {{ name }} we are glad to tell you {{ message }}


I would like to have an array like this:

["hello", "{{salutation}}", "{{ name }}", "we are glad to tell you", "{{ message }}"]


Is this possible in with native functions? or do i have to make a workaround?

Answer Source

You could adapt the answer of Split around curly braces with search for more curly brackets and inside with any characters except a closing curly bracket

var string = 'hello {{salutation}} {{ name }} we are glad to tell you {{ message }}',
    array = string.split(/\s*(\{\{[^}]+}})\s*/).filter(Boolean);
    
console.log(array);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download