Js String.Split() Without Removing the Delimiters

JS string.split() without removing the delimiters

Try this:

  1. Replace all of the "d" instances into ",d"
  2. Split by ","
var string = "abcdeabcde";
var newstringreplaced = string.replace(/d/gi, ",d");
var newstring = newstringreplaced.split(",");
return newstring;

Hope this helps.

how to split a string without delimiters?

You can just .split() with an empty string as the delimiter. This will split the string at each character:

function nextBigger(num){  console.log(num.toString().split(""));}
nextBigger(513);

Split string into array without deleting delimiter?

Instead of splitting, it might be easier to think of this as extracting strings comprising either the delimiter or consecutive characters that are not the delimiter:

'asdf a  b c2 '.match(/\S+|\s/g)
// result: ["asdf", " ", "a", " ", " ", "b", " ", "c2", " "]
'asdf a b. . c2% * '.match(/\S+|\s/g)
// result: ["asdf", " ", "a", " ", " ", "b.", " ", ".", " ", "c2%", " ", "*", " "]

A more Shakespearean definition of the matches would be:

'asdf a  b c2 '.match(/ |[^ ]+/g)

To or (not to )+.

JS / TS splitting string by a delimiter without removing the delimiter

You could split by positive lookahead of #.

var string = "#mavic#phantom#spark",    splitted = string.split(/(?=#)/);
console.log(splitted);

javascript - split without losing the separator

Try this. It's not a perfect solution, but it should work in most cases.

str.split(/(?=<foo>)/)

That is, split it in the position before each opening tag.

EDIT: You could also do it with match(), like so:

str.match(/<foo>.*?<\/bar>/g)

Split a string based on substring delimiter, keeping the delimiter in the result

You could take a positive lookahead.

var string = "choc: 123 choc: 328 choc: 129";console.log(string.split(/(?=choc)/));

How can I split a string without losing the separator and without regex?

Since javascript regex doesn't support look behind assertion it's not possible with String#split method. Use String#match method to get the complete string.

var arr = "<p></p>".match(/[\s\S]+?>(?=<|$)/g)
console.log(arr)

How do I split a string with multiple separators in JavaScript?

Pass in a regexp as the parameter:

js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!

Edited to add:

You can get the last element by selecting the length of the array minus 1:

>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"

... and if the pattern doesn't match:

>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"


Related Topics



Leave a reply



Submit