Gregory R.
Gregory R.

Reputation: 1935

How to get the delimiters that split my string in Javascript?

Let's say I have a string like the following:

var str = "hello=world&universe";

And my regex replace statement goes like this:

str.replace(/([&=])/g, ' ');

How do I get the delimiters that split my string from the above regex replace statement?

I would like the result to be something like this:

var strings    = ['hello', 'world', 'universe'];
var delimiters = ['=', '&'];

Upvotes: 0

Views: 57

Answers (2)

user128511
user128511

Reputation:

Here's one way using String.matchAll

const str = "hello=world&universe";
const re = /([&=])/g;
const matches = [];
let pos = 0;
const delimiters = [...str.matchAll(re)].map(m => {
  const [match, capture] = m;
  matches.push(str.substring(pos, m.index));
  pos = m.index + match.length;
  return match;  
});
matches.push(str.substring(pos));

console.log('matches:', matches.join(', '));
console.log('delimiters:', delimiters.join(', '));

But just FYI. The string you posted looks like a URL search string. You probably want to use URLSearchParams to parse it as there are edge cases if you try to split on both '&' and '=' at the same time. See How can I get query string values in JavaScript?

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could split with a group and then separate the parts.

var str = "hello=world&universe",
    [words, delimiters] = str
        .split(/([&=])/)
        .reduce((r, s, i) => {
            r[i % 2].push(s);
            return r;    
        }, [[], []]);

console.log(words);
console.log(delimiters);

Upvotes: 2

Related Questions