Modifying a string by replacing - javascript

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

Related

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, "\""));

Regex equivalent to str.substr(0, str.indexOf('foo'))

Given this string:
var str = 'A1=B2;C3,D0*E9+F6-';
I would like to retrieve the substring that goes from the beginning of the string up to 'D0*' (excluding), in this case:
'A1=B2;C3,'
I know how to achieve this using the combination of the substr and indexOf methods:
str.substr(0, str.indexOf('D0*'))
Live demo: http://jsfiddle.net/simevidas/XSu22/
However, this is obviously not the best solution since it contains a redundancy (the str name has to be written twice). This redundancy can be avoided by using the match method together with a regular expression that captures the substring:
str.match(/???/)[1]
Which regular expression literal do we have to pass into match to ensure that the correct substring is returned?
My guess is this: /(.*)D0\*/ (and that works), but my experience with regular expressions is rather limited, so I'm going to need a confirmation...
Try this:
/(.*?)D0\*/.exec(str)[1]
Or:
str.match(/(.*?)D0\*/)[1]
DEMO HERE
? directly following a quantifier makes the quantifier non-greedy (makes it match minimum instead of maximum of the interval defined).
Here's where that's from
/^(.+?)D0\*/
Try it here: http://rubular.com/r/TNTizJLSn9
/^.*(?=D0\*)/
more text to hit character limit...
You can do a number-group, like your example.
/^(.*?)foo/
It mean somethink like:
Store all in group, from start (the 0)
Stop, but don't store on found foo (the indexOf)
After that, you need match and get
'hello foo bar foo bar'.match(/^(.*?)foo/)[1]; // will return "hello "
It mean that will work on str variable and get the first (and unique) number-group existent. The [0] instead [1] mean that will get all matched code.
Bye :)

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

how to simplfy this code

What would be a good way to do this. I have a string with lots of "<" and > and I want to replace them with < and >. So i wrote this:
var str = </text><word34212>
var p = str.replace('\&lt\;','\<');
var m = p.replace('\&gt\;','\>');
but that's just doing the first instance of each - and subsequent instances of </> are not replaced. I considered first counting the instances of the < and then looping and replacing one instance of the code on every iteration...and then doing the same for the > but obviously this is quite long-winded.
Can anyone suggest a neater way to do this?
To replace multiple occurances you use a regular expression, so that you can specify the global (g) flag:
var m = str.replace(/</g,'<').replace(/>/g,'>');
Taken from: http://www.bradino.com/javascript/string-replace/
The JavaScript function for String
Replace replaces the first occurrence
in the string. The function is similar
to the php function str_replace and
takes two simple parameters. The first
parameter is the pattern to find and
the second parameter is the string to
replace the pattern with when found.
The javascript function does not
Replace All...
To ReplaceAll you have to do it a
little differently. To replace all
occurrences in the string, use the g
modifier like this:
str = str.replace(/find/g,”replace”)
You need to use the global modifier:
var p = str.replace(/\&lt\;/g,'\<');
You need to use de /g modifier in your regex and it'll work. Check this page for an example : http://www.w3schools.com/jsref/jsref_replace.asp
I thing a associative array [regex -> replacement] and one iteration would do it

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