0

Hello regex experts!

Question One I want to find the sub string 'delimiter' and remove it as well as anything following it so the result is 'fredrobert'

var originalstring = 'fredrobertdelimitergarysusan';
var result = orig.match(/* not sure what goes here*/);              
console.log('result = ',result); //fredrobert

Question Two I want to find the sub string 'delimiter' and remove it as well as anything preceding it so the result is 'garysusan'

var originalstring = 'fredrobertdelimitergarysusan';
var result = orig.match(/* not sure what goes here*/);              
console.log('result = ',result); //garysusan

Question Three I want to find the sub strings 'delimiterA' and 'delimiterB' remove them as well as what is betweenso the result is 'fredsusan'

var originalstring = 'freddelimiterArobertgarydelimiterBsusan';
var result = orig.match(/* not sure what goes here*/);              
console.log('result = ',result);  //fredsusan
1
  • You could use the string-indexing function for a couple of these and search for the substring delimiter, then take a substring either up to or after that location (plus delimiter length). For the third one, consider /^(.*?)delimiter.*delimiter(.*?)$/ Commented Feb 13, 2014 at 16:40

2 Answers 2

1

The key here is to use .replace(), not .match(). .match() finds text that matches a pattern, but doesn't replace it. .replace(), well, it replaces it!

Question One

Use .replace(), not .match():

var originalstring = 'fredrobertdelimitergarysusan';
var result = orig.replace(/delimiter.*/, '');              
console.log('result = ',result); //fredrobert

Question Two

Again, use .replace():

var originalstring = 'fredrobertdelimitergarysusan';
var result = orig.replace(/.*delimiter/, '');
console.log('result = ',result); //garysusan

Question Three

Use .replace() with .* between delimiters:

var originalstring = 'freddelimiterArobertgarydelimiterBsusan';
var result = orig.replace(/delimiterA.*delimiterB/, '');              
console.log('result = ',result);  //fredsusan
Sign up to request clarification or add additional context in comments.

1 Comment

excellent, this works. here is the jsfiddle of this http://jsfiddle.net/s7H9v/2/
0

Match the word "delimiter" and everything after it, to the end of the string:

/delimiter.*$/

"delimiter" and everything preceding it:

/^.*delimiter/

"delimiterA," "delimiterB" and everything between:

/delimiterA.*delimiterB/

1 Comment

this didn't work see this jsfiddle and watch console link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.