0

If I have this string: "MyStringToForSplitting" and I want to split it by this word "ring". If I do this: "MyStringToForSplitting".split('ring') I will get array that contains this elements:

  1. MyS
  2. ToForSplitting

I can't figure out best way to split it and include 'ring' in resulting array like this:

1.MyS

2.ring

3.ForSplitting

1
  • Sorry for duplication. Didn't find that one... Commented Jul 14, 2017 at 18:02

1 Answer 1

6

You can use regex and capture the split pattern:

console.log("MyStringToForSplitting".split(/(ring)/));

var s = "ring";
var p = new RegExp("(" + s + ")")
console.log("MyStringForSplitting".split(p))

Sign up to request clarification or add additional context in comments.

3 Comments

What is ring is variable not hardcoded string?
You can construct the regular expression from the string variable and then use it for split. See the update.
And if you want to ignore casing then new RegExp("(" + s + ")","i") can be used

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.