Solved

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

Posted on 2014-04-23
3
447 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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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…

757 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now