Solved

JavaScript/REGEX: remove all words that do not begin with xyz

Posted on 2014-04-23
3
451 Views
Last Modified: 2014-04-23
Using Regular Expressions and JavaScript, how can I remove all words that do not begin with xyz?
var str = 'xyz1 xyz2 xyzzy hello world xyz555 xyzttt';
str = str.replace(???????????????????????????????????);
alert(str); // should be: hello world

Open in new window

0
Comment
Question by:hankknight
  • 2
3 Comments
 
LVL 35

Assisted Solution

by:Terry Woods
Terry Woods earned 250 total points
ID: 40018854
Going by the title of the question:
var str = 'xyz1 xyz2 xyzzy hello world xyz555 xyzttt';
str = str.replace(/\b(?!xyz)\w+/g, '');
alert(str);

Open in new window

Result is:
xyz1 xyz2 xyzzy   xyz555 xyzttt

Open in new window


Going by the comment in your starting code:
var str = 'xyz1 xyz2 xyzzy hello world xyz555 xyzttt';
str = str.replace(/\bxyz\w+/g, '');
alert(str); // should be: hello world

Open in new window

Result is:
hello world

Open in new window

0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 40018861
Let me know if you want the space for any invalid words removed too.
0
 
LVL 42

Accepted Solution

by:
David S. earned 250 total points
ID: 40018874
You may be other-thinking it, Terry. You do want to match the "xyz". Also "\b" won't work as intended here because, at least in JavaScript RegEx, a hyphen is counted as a word-boundary.
str = str.replace(/(^|\s+)xyz\S*/g, '');

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question