Regular expressions for parsing "real" words in JavaScript - 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.".

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(/ +/)

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);
});

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.

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

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++) {
}

Related

How do I return array of strings from strings enclosed in square brackets

So I have a string that follows "[option1] [option2] [option3] some more text", how would I extract a array of strings from that string that goes like this ["option1", "option2", "option3"] its a bit late at night so I'm sorry if I phrased this question badly, thanks for the help!
You can pass a regular expression to the string match method to do this. This uses both lookahead (?=\]) and lookbehind (?<=\[) operators to check for brackets but not include those brackets in the result. Then, you want to lazily capture everything in between the brackets .+?. The g makes sure we do this globally (look for all matches, not just the first).
const str = "[option1] [option2] [option3] some more text";
const matches = str.match(/(?<=\[).+?(?=\])/g);
console.log(matches);
Javascript has a split function you can use to split a string into an array just do this
var nameOfString = "[option option option]"
let newString = nameOfString.replace(/[/g, "").replace(/]/g, "").split(" ");
then you can do newString[0] first word etc...

find and remove words matching a substring in a sentence

Is it possible to use regex to find all words within a sentence that contains a substring?
Example:
var sentence = "hello my number is 344undefined848 undefinedundefined undefinedcalling whistleundefined";
I need to find all words in this sentence which contains 'undefined' and remove those words.
Output should be "hello my number is ";
FYI - currently I tokenize (javascript) and iterate through all the tokens to find and remove, then merge the final string. I need to use regex. Please help.
Thanks!
You can use:
str = str.replace(/ *\b\S*?undefined\S*\b/g, '');
RegEx Demo
It certainly is possible.
Something like start of word, zero or more letters, "undefined", zero or more letters, end of word should do it.
A word boundary is \b outside a character class, so:
\b\w*?undefined\w*?\b
using non-greedy repetition to avoid the letter matching tryig to match "undefined" and leading to lots of backtracking.
Edit switch [a-zA-Z] to \w because the example includes numbers in the "words".
\S*undefined\S*
Try this simple regex.Replace by empty string.See demo.
https://www.regex101.com/r/fG5pZ8/5
you can use str.replace function like this
str = str.replace(/undefined/g, '');
Since there are enough solutions with regular expressions, here is another one - using arrays and simple function that finds occurrence of a string in a string :)
Even though the code looks more "dirty", it actually works faster than regular expression, so it might make sense to consider it when dealing with LARGE strings
var sentence = "hello my number is 344undefined848 undefinedundefined undefinedcalling whistleundefined";
var array = sentence.split(' ');
var sanitizedArray = [];
for (var i = 0; i <= array.length; i++) {
if (undefined !== array[i] && array[i].indexOf('undefined') == -1) {
sanitizedArray.push(array[i]);
}
}
var sanitizedSentence = sanitizedArray.join(' ');
alert(sanitizedSentence);
Fiddle: http://jsfiddle.net/448bbumh/

Replace string using regular expression at specific position dynamically set

I want to use regular expression to replace a string from the matching pattern string.
Here is my string :
"this is just a simple text. this is just a simple text. this is just a simple text. this is just a simple text. How are you man today. I Have been working on this."
Now, I have a situation that, I want to replace "just a simple" with say "hello", but only in the third occurrence of a string. So can anyone guide me through this I will be very helpful. But the twist comes here. The above string is dynamic. The user can modify or change text.
So how can I check, if the user add "this is just a simple text" one or more times at the start or before the third occurrence of string which changes my string replacement position?
Sorry if I am unclear; But any guidance or help or any other methods will be helpful.
You can use this regex:
(?:.*?(just a simple)){3}
Working demo
You can use replace with a dynamically built regular expression and a callback in which you count the occurrences of the searched pattern :
var s = "this is just a simple text. this is just a simple text. this is just a simple text. this is just a simple text. How are you man today. I Have been working on this.",
pattern = "just a simple",
escapedPattern = pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
i=0;
s = s.replace(new RegExp(escapedPattern,'g'), function(t){ return ++i===3 ? "hello" : t });
Note that I used this related QA to escape any "special" characters in the pattern.
Try
$(selector)
.data("r", ["simple text", 3, "hello"])
.text(function (i, o) {
var r = $(this).data("r");
return o.replace(new RegExp(r[0], "g"), function (m) {
++i;
return (i === r[1]) ? r[2] : m
})
}).data("r", []);
jsfiddle http://jsfiddle.net/guest271314/2fm91qox/
See
Find and replace nth occurrence of [bracketed] expression in string
Replacing the nth instance of a regex match in Javascript
JavaScript: how can I replace only Nth match in the string?

Modifying a string by replacing

How can I replace some words in a string with some other words? For example:
var text1 = "This is a sentence. It is a pencil."
text2 = modify(text1);
I want text2 to be "That was a sentence. I was a pencil."
So modify function replaces This->That , is->was
To replace all instances of the substring is with was you can use the replace[MDN] method:
text2 = text1.replace(/is/g, "was");
Note that because is is a part of the word this, it will actually return
Thwas was a sentence
If you wanted to replace all instances of This to That and is to was, you could chain the calls to the replace method.
text2 = text1.replace(/This/g, "That").replace(/is/g, "was");
This will correctly do your replacement from
This is a sentence. It is a pencil.
to
That was a sentence. It was a pencil.
You can see this in action on jsFiddle.
Note that find and replace actions like this can always have unintended consequences. For example, this string
Thistles and thorns are bad for missiles and corns.
will turn into this one after your replacement:
Thatles and thorns are bad for mwassiles and corns.
This sort of thing is popularly known as the Clbuttic mistake.
text1 = text1.replace('is', 'was');
Btw, .replace accepts regular expressions as well
Utilize the javascript replace method -
http://www.w3schools.com/jsref/jsref_replace.asp
Note: To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter.
You could use javascript's Replace function like this:
var text2 = text1.replace('is','was');

Finding a word and replacing using regular expressions in javascript

I need information about finding a word and replacing it with regular expressions in javascript.
You can use \b to specify a word boundary. Just put them around the word that you want to replace.
Example:
var s = "That's a car.";
s = /\ba\b/g.replace(s, "the");
The variable s now contains the string "That's the car". Notice that the "a" in "That's" and "car" are unaffected.
Since you haven't really asked a question, the best I can do is point you here:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
And tell you also that the replace method for a string is replace, as in:
var myStr = "there is a word in here";
var changedStr = myStr.replace(/word/g, "replacement");

Categories

Resources