Finding a word and replacing using regular expressions in javascript - 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");

Related

Check first character of a word in a string begins with #

A few days ago I posted a similar question, but I do not quite understand the principle. Are there good resources where the replace function combined with regular expressions is explained?
Anyways, right now I have the following problem: A string which starts with # should be placed in an link. So #test should be replaced to #test .
Also, these rules should apply:
The string can only contain one #, which is at the beginning.
If there are more strings, also replace them. I thought you can do this by putting /g behind the regex?
This is what I have so far:
value = "is #test";
var text = value.replace(/^.*(#)(\w+).*$/, "<a href='$2'>$1$2</a>");
My output
#test
EDIT:
The link is now working. However, the word "is" is missing.
You need to capture the ambient text:
value = "is #test or what";
var text = value.replace(/^(.*)#(\w+)(.*)$/, "$1<a href='$2'>#$2</a>$3");
Or just capture less:
var text = value.replace(/#(\w+)/, "<a href='$1'>#$1</a>");
When performing a .replace(), you need to include all the characters in the RegExp that you wish to replace, preserving the ones you want to keep with parentheses.
var test = 'is #test';
function makeAt(string){
return string.replace(/^.*(#)(\w+).*$/, "<a href='$2'>$1$2</a>");
}
console.log(makeAt(test));

Regex to change quoting style

In the text that I get, I want to replace all the dialogue quotes with double quotes, while keeping the single quotes used in contractions like "aren’t". I want to use a String.replace() with a regular expression to do this..
E:g:
var text = "'I'm the cook,' he said, 'it's my job.'";
console.log(text.replace(/*regEx*/, "\""));
//should return → "I'm the cook," he said, "it's my job."
Now I know a regex that works for me, at least for the example text.
console.log(text.replace(/\B'/g, "\""));
However, I wonder if there is any other regex I can use to accomplish this. Just curious.
I noticed that the regular expression you provided doesn't replace single quotes in the beginning of the string. I came up with this one instead:
var str = "'Hello', - she said\n'Hi!' - he whispered\n";
console.log(str.replace(/\B'|'\B/g, "\""));

Match a string if it comes after certain string

I need a regular expression for JavaScript to match John (case insensitive) after Name:
I know how to do it, but I don't know how to get string from a different line like so (from a textarea):
Name
John
This is what I tried to do :: var str = /\s[a-zA-Z0-9](?= Name)/;
The logic: get a string with letter/numbers on a linespace followed by Name.
Then, I would use the .test(); method.
EDIT:
I tried to make the question more simple than it should have been. The thing I don't quite understand is how do I isolate "John" (really anything) on a new line followed by a specific string (in this case Name).
E.g., IF John comes after Name {dosomething} else{dosomethingelse}
Unfortunately, JavaScript doesn't support look-behinds. For something this simple, you can just match both parts of the string like this:
var str = /Name\s+([a-zA-Z0-9]+)/;
You then just have to extract the first capture group if you want to get John. For example:
"Name\n John".match(/Name\s+([a-zA-Z0-9]+)/)[1]; // John
However if you're just using .test, the capture group isn't necessary. For example:
var input = "Name\n John";
if (/Name\s+[a-zA-Z0-9]+/.test(input)) {
// dosomething
} else{
// dosomethingelse
}
Also, if you need to ensure that Name and John appear on separate lines with nothing but whitespace in between, you can use this pattern with the multi-line (m) flag.
var str = /Name\s*^\s*([a-zA-Z0-9]+)/m;
You do not need a lookahead here, simply place Name before the characters you want to match. And to enable case-insensitive matching, place the i modifier on the end of your regular expression.
var str = 'Name\n John'
var re = /Name\s+[a-z0-9]+/i
if (re.test(str)) {
// do something
} else {
// do something else
}
Use the String.match method if you want to extract the name from the string.
'Name\n John'.match(/Name\s+([a-z0-9]+)/i)[1];
The [1] here refers back to what was matched/captured in capturing group #1

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

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

Categories

Resources