High T
High T

Reputation: 61

Can I slice a string from a certain word in JavaScript, no matter how many characters/words are preceding it?

I have two strings:

var string1 = "The quick brown fox jumps over the lazy dog.";

var string2 = "The sluggish, purple fox jumps over a rapid cat.";

Is there a way to get all the words from "fox" in both cases? split() does not work here, because it takes the exact position of the first letter of fox, "f". But that's the point, what if the length of words preceding "fox" are different, and the position of "f" changes? So I want everything after "fox" in every cases, whether the word starts at position 0, 2, 3, 5, 8 etc.

Upvotes: 0

Views: 797

Answers (2)

lejlun
lejlun

Reputation: 4419

You can do this using String#match and a Regular Expression:

var string1 = "The quick brown fox jumps over the lazy dog.";
var string2 = "The sluggish, purple fox jumps over a rapid cat.";

const regex = /\bfox\b .*/;

console.log(string1.match(regex));
console.log(string2.match(regex));

If you don't want to include fox in the returned string, you could use this regex instead:

var string1 = "The quick brown fox jumps over the lazy dog.";
var string2 = "The sluggish, purple fox jumps over a rapid cat.";

const regex = /(?<=\bfox\b ).*/;

console.log(string1.match(regex));
console.log(string2.match(regex));

Upvotes: 2

Andy Bonner
Andy Bonner

Reputation: 127

Passing a substring as an argument to String.split() will return an array of the portions of the original string coming before or after that argument, if any.

string1.split('fox') // -> ['The quick brown ', ' jumps over the lazy dog']
string2.split('fox') // -> ['The sluggish, purple ', ' jumps over a rapid cat']

(But beware:)

'The foxy fox jumps foxily'.split('fox') // -> ["The ", "y ", " jumps ", "ily"]

Upvotes: 1

Related Questions