HiveHicks
HiveHicks

Reputation: 2334

Regular expressions for parsing "real" words in JavaScript

I've got some text where some words are "real" words, and others are masks that will be replaced with some text and that are surrounded with, say, "%". Here's the example:

Hello dear %Name%! You're %Age% y.o.

What regular expression should I use to get "real" words, without using lookbehind, because they don't exist in JavaScript?

UPD: I want to get words "Hello", "dear", "you're", "y.o.".

Upvotes: 2

Views: 331

Answers (5)

Buhake Sindi
Buhake Sindi

Reputation: 89189

Use regular expression in Javascript and split the string based on matching regular expression.

//javascript
var s = "Hello dear %Name%! You're %Age% y.o.";
words = s.split(/%[^%]*?%/i);

//To get all the words
for (var i = 0; i < words.length; i++) {

}

Upvotes: 0

Ben
Ben

Reputation: 1127

You can match the %Something% matches using %[^%]*?%, but how are you storing all of the individual mask values like Name and Age?

Upvotes: 0

Todd Moses
Todd Moses

Reputation: 11039

To do a search and replace with regexes, use the string's replace() method:

myString.replace(/replaceme/g, "replacement")

Using the /g modifier makes sure that all occurrences of "replaceme" are replaced. The second parameter is an normal string with the replacement text.

Upvotes: 0

Gumbo
Gumbo

Reputation: 655519

You could use split to get the words and filter the words afterwards:

var str = "Hello dear %Name%! You're %Age% y.o.", words;
words = str.split(/\s+/).filter(function(val) {
    return !/%[^%]*%/.test(val);
});

Upvotes: 1

ase
ase

Reputation: 13481

If I've understood your question correctly this might work.

I would go about it the other way around, instead of finding the real words I would remove the "fake-words."

s = "Hello dear %Name%! You're %Age% y.o."
realWords = s.replace(/%.*?%/g, "").split(/ +/)

Upvotes: 1

Related Questions