Make translation function not translate result again - javascript

I have made this very simplified version of a translation tool similar to Google Translate. The idea is to build this simple tool for a minority language in sweden called "jamska". The app is built up with a function that takes the string from a textarea with the ID #svenska and replaces words in the string using RegExp.
I've made an array called arr that's used in a for loop of the function as a dictionary. Each array item looks like this: var arr = [["eldröd", "eillrau"], ["oväder", "over"] ...]. The first word in each array item is in swedish, and the second word is in jamska. If the RegExp finds a matching word in the loop it replaces that word using this code:
function translate() {
var str = $("#svenska").val();
var newStr = "";
for (var i = 0; i < arr.length; i++) {
var replace = arr[i][0];
var replaceWith = arr[i][1];
var re = new RegExp('(^|[^a-z0-9åäö])' + replace + '([^a-z0-9åäö]|$)', 'ig');
str = str.replace(re, "$1" + replaceWith + '$2');
}
$("#jamska").val(str);
}
The translate() is then called in an event handler for when the #svenska textarea gets a keyup, like this: $("#svenska").keyup(function() { translate(); });
The translated string is then assigned as the value of another textarea with the ID #jamska. So far, so good.
I have a problem though: if the translated word in jamska also is a word in swedish, the function translates that word too. This problem is occurring because I'm assigning the variable str to the translated version of the same variable, using: str = str.replace(re, "$1" + replaceWith + '$2');. The function is using the same variable over and over again to perform the translation.
Example:
The swedish word "brydd" is "fel" in jamska. "Fel" is also a word in swedish, so the word that I get after the translation is "felht", since the swedish word "fel" is "felht" in jamska.
Does anyone have any idea for how to work around this problem?

Instead of looking for each Jamska word in the input and replacing them with the respective translation, I would recommend to find any word ([a-z0-9åäö]+) in your text and replace this word either with its translation if one is found in the dictionary or with itself otherwise:
//var arr = [["eldröd", "eillrau"], ["oväder", "over"] ...]
// I'd better use dictionary instead of array to define your dictionary
var dict = {
eldröd: "oväder",
eillrau: "over"
// ...
};
var str = "eldröd test eillrau eillrau oväder over";
var translated = str.replace(/[a-z0-9åäö]+/ig, function(m) {
var word = m.toLowerCase();
var trans = dict[word];
return trans === undefined ? word : trans;
});
console.log(translated);
Update:
If dictionary keys may be represented by phrases (i.e. technically appear as strings with spaces), the regex should be extended to include all these phrases explicitly. So the final regex would look like
(?:phrase 1|phrase 2|etc...)(?![a-z0-9åäö])|[a-z0-9åäö]+
It will try to match one of the phrases explicitly first and only then single words. The (?![a-z0-9åäö]) lookbehind helps to filter out phrases immediately followed by letters (e.g. varken bättre eller sämreåäö).
Phrases immediately preceded by letters are implicitly filtered out by the fact that a match is either the fist one (and therefore is not preceded by any letter) or it's not the first and therefore the previous one is separated from the current by some spaces.
//var arr = [["eldröd", "eillrau"], ["oväder", "over"] ...]
// I'd better use dictionary instead of array to define your dictionary
var dict = {
eldröd: "oväder",
eillrau: "over",
bättre: "better",
"varken bättre eller sämre": "vär å int viller",
"test test": "double test"
// ...
};
var str = "eldröd test eillrau eillrau oväder over test test ";
str += "varken bättre eller sämre ";
str += "don't trans: varken bättre eller sämreåäö";
str += "don't trans again: åäövarken bättre eller sämre";
var phrases = Object.keys(dict)
.filter(function(k) { return /\s/.test(k); })
.sort(function(a, b) { return b.length - a.length; })
.join('|');
var re = new RegExp('(?:' + phrases + ')(?![a-z0-9åäö])|[a-z0-9åäö]+', 'ig');
var translated = str.replace(re, function(m) {
var word = m.toLowerCase();
var trans = dict[word];
return trans === undefined ? word : trans;
});
console.log(translated);

Related

Transform string of text using JavaScript

I am working on a code to transform a string of text into a Sentence case which would also retain Acronyms. I did explore similar posts in StackOverflow, however, I couldn't find the one which suits my requirement.
I have already achieved the transformation of Acronyms and the first letter in the sentence. however, I ran into other issues like some letters in the sentence are still in Uppercase, especially texts in and after Double Quotes (" ") and camelcase texts.
Below is the code I am currently working on, I would need someone to help me Optimize the code and to fix the issues.
String.prototype.toSentenceCase = function() {
var i, j, str, lowers, uppers;
str = this.replace(/(^\w{1}|\.\s*\w{1})/gi, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv', 'Nasa', 'Acronyms'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
// To remove Special caharacters like ':' and '?'
str = str.replace(/[""]/g,'');
str = str.replace(/[?]/g,'');
str = str.replace(/[:]/g,' - ');
return str;
}
Input: play around: This is a "String" Of text, which needs to be cONVERTED to Sentence Case at the same time keeping the Acronyms as it is like Nasa.
Current Output: Play around - This is a String Of text, which needs to be cONVERTED to Sentence Case at the same time keeping the ACRONYMS as it is like NASA.
Expected Output: Play around - this is a string of text, which needs to be converted to sentence case at the same time keeping the ACRONYMS as it is like NASA.
Here's a runnable version of the initial code (I have slightly modified the input string):
String.prototype.toSentenceCase = function() {
var i, j, str, lowers, uppers;
str = this.replace(/(^\w{1}|\.\s*\w{1})/gi, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv', 'Nasa', 'Acronyms'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
// To remove Special caharacters like ':' and '?'
str = str.replace(/[""]/g,'');
str = str.replace(/[?]/g,'');
str = str.replace(/[:]/g,' - ');
return str;
}
const input = `play around: This is a "String" Of text, which needs to be cONVERTED to Sentence Case at the same time keeping the Acronyms as it is like Nasa. another sentence. "third" sentence starting with a quote.`
const result = input.toSentenceCase()
console.log(result)
I ran into other issues like some letters in the sentence are still in Uppercase, especially texts in and after Double Quotes (" ") and camelcase texts.
Some letters remain uppercased because you are not calling .toLowerCase() anywhere in your code. Expect in the beginning, but that regex is targetingonly the initial letters of sentences, not other letters.
It can be helpful to first lowercase all letters, and then uppercase some letters (acronyms and initial letters of sentences). So, let's call .toLowerCase() in the beginning:
String.prototype.toSentenceCase = function() {
var i, j, str, lowers, uppers;
str = this.toLowerCase();
// ...
return str;
}
Next, let's take a look at this regex:
/(^\w{1}|\.\s*\w{1})/gi
The parentheses are unnecessary, because the capturing group is not used in the replacer function. The {1} quantifiers are also unnecessary, because by default \w matches only one character. So we can simplify the regex like so:
/^\w|\.\s*\w/gi
This regex finds two matches from the input string:
p
. a
Both matches contain only one letter (\w), so in the replacer function, we can safely call txt.toUpperCase() instead of the current, more complex expression (txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()). We can also use an arrow function:
String.prototype.toSentenceCase = function() {
var i, j, str, lowers, uppers;
str = this.toLowerCase();
str = str.replace(/^\w|\.\s*\w/gi, (txt) => txt.toUpperCase());
// ...
return str;
}
However, the initial letter of the third sentence is not uppercased because the sentence starts with a quote. Because we are anyway going to remove quotes and question marks, let's do it at the beginning.
Let's also simplify and combine the regexes:
// Before
str = str.replace(/[""]/g,'');
str = str.replace(/[?]/g,'');
str = str.replace(/[:]/g,' - ');
// After
str = str.replace(/["?]/g,'');
str = str.replace(/:/g,' - ');
So:
String.prototype.toSentenceCase = function() {
var i, j, str, lowers, uppers;
str = this;
str = str.toLowerCase();
str = str.replace(/["?]/g,'');
str = str.replace(/:/g,' - ');
str = str.replace(/^\w|\.\s*\w/gi, (txt) => txt.toUpperCase());
// ...
return str;
}
Now the initial letter of the third sentence is correctly uppercased. That's because when we are uppercasing the initial letters, the third sentence doesn't start with a quote anymore (because we have removed the quote).
What's left is to uppercase acronyms. In your regex, you probably want to use the i flag as well for case-insensitive matches.
Instead of using a for loop, it's possible to use a single regex to look for all matches and uppercase them. This allows us to get rid of most of the variables as well. Like so:
String.prototype.toSentenceCase = function() {
var str;
str = this;
str = str.toLowerCase();
str = str.replace(/["?]/g,'');
str = str.replace(/:/g,' - ');
str = str.replace(/^\w|\.\s*\w/gi, (txt) => txt.toUpperCase());
str = str.replace(/\b(id|tv|nasa|acronyms)\b/gi, (txt) => txt.toUpperCase());
return str;
}
And looks like we are now getting correct results!
Three more things, though:
Instead of creating and mutating the str variable, we can modify this and chain the method calls.
It might make sense to rename the txt variables to match variables, since they are regex matches.
Modifying a built-in object's prototype is a bad idea. Creating a new function is a better idea.
Here's the final code:
function convertToSentenceCase(str) {
return str
.toLowerCase()
.replace(/["?]/g, '')
.replace(/:/g, ' - ')
.replace(/^\w|\.\s*\w/gi, (match) => match.toUpperCase())
.replace(/\b(id|tv|nasa|acronyms)\b/gi, (match) => match.toUpperCase())
}
const input = `play around: This is a "String" Of text, which needs to be cONVERTED to Sentence Case at the same time keeping the Acronyms as it is like Nasa. another sentence. "third" sentence starting with a quote.`
const result = convertToSentenceCase(input)
console.log(result)

Using simple angular filter to replace all occurences of certain strings in input string regardless of case and whitespaces

On my website I have a commentary field, where people can write whatever they want. To prevent spam and unserious comments, I'm using an angular filter in this way:
<span>{{comment | mouthWash}}</span>
The angular filter fetches an array containing banned words and scans through the input string and replaces all the occurences of the fetched words. The code for the filter is as below:
app.filter('mouthWash', function($http) {
var badWords;
$http.get('js/objects/bad-words.json').success(function (data) {
badWords = data;
});
return function(input) {
angular.forEach(badWords, function(word){
var regEx = new RegExp(word);
input = input.replace(regEx, "mooh");
});
return input;
};
});
bad-words.json is something like this:
["fuck", "ass", "shit", etc...]
So as an example <span>{{ "fuck this" | mouthWash}}</span> is outputted as <span>mooh this</span>
This is working perfectly, except that I want it to ignore whitespaces, to make it more bullet proof. I do not have much experience with regex, so if anyone had a simple soloution to this, I would be really grateful.
just change new RegExp(word, "ig"); to new RegExp("ig");
working example:
var words = ['pig', 'dog', '', ' ', 'cow'];
words.forEach(function(word) {
var regEx = new RegExp("ig");
word = word.replace(regEx, "mooh");
console.log(word);
});
Output:
"pmooh"
"dog"
""
" "
"cow"
This is the code I ended up with:
app.filter('mouthWash', function($http) {
var badWords;
$http.get('js/objects/bad-words.json').success(function (data) {
badWords = data;
});
return function(input) {
angular.forEach(badWords, function(word){
var str = word.substring(0,1)+"\\s*";
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
str = str + word.substring(word.length - 1,word.length);
var regEx = new RegExp(str, "gi");
input = input.replace(regEx, "mooh");
});
return input;
};
});
I created a for loop that would loop through every character of the banned word, adding the character together with \s* (so that spaces was ignored) to a string.
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
Then created a regExp from the string, by using the regExp constructor with the string as first parameter and "gi" as second, to make the regExp global and case insensitive.
var regEx = new RegExp(str, "gi");
Then that regex was used to search through input string and replace all matches with "mooh".

search for keyword in extracted text javascript

So I managed to extract some text, and then I saved it as a variable for later use, how can I test for certain keywords within said text?
Here's an example, checkTitle is the text I extracted, and I want to search it for certain keywords, in this example, the words delimited by commas within compareTitle. I want to search for the strings '5' and 'monkeys'.
var checkTitle = "5 monkeys jumping on the bed";
var compareTitle = "5 , monkeys";
if (checkTitle === compareTitle) {
// ...
}
You can use regular expressions to search for strings, and the test() function to return true/false if the string contains the words.
/(?:^|\s)(?:(?:monkeys)|(?:5))\s+/gi.test("5 monkeys jumping on the bed");
will return true, because the string contains either (in this case, both) the words 5 and monkeys.
See my example here: http://regexr.com/39ti7 to use the site's tools to analyse each aspect of the regular expression.
If you need to change the words you are testing for each time, then you can use this code:
function checkForMatches(){
var words = checkTitle.split(" , ");
var patt;
for (var i = 0; i < words.length; i++){
patt = patt + "(" + words[i] + ")|";
}
patt[patt.length-1] = "";
patt = new RegExp(patt, "i");
return patt.test(checkTitle);
}
will return true, and allow for any words you want to be checked against. They must be separated like this:
compareText = "word1 , word2 , word3 , so on , ...";
// ^^^notice, space-comma-space.
And you can use it in an if statement like this:
var checkTitle = "5 monkeys jumping on the bed";
var compareTitle = "5 , monkeys";
if (checkForMatches()){
//a match was found!
}
Using the String.prototype.contains() method you can search for substrings within strings. For example,
"Hi there everyone!".contains("Hi"); //true
"Hi there everyone!".contains("there e"); //true
"Hi there everyone!".contains("goodbye"); //false
You can also use Array.prototype.indexOf() to a similar effect:
("Hi there everyone!".indexOf("Hi") > -1) //true
("Hi there everyone!".indexOf("Hmmn") > -1) //false
However, in this method, we don't even need to use any of the above methods, as the .match() method will do it all for us:
To return an array of the matched keywords, use .match(). It accepts a regular expression as an argument, and returns an array of substrings which match the regular expression.
var checkTitle = "5 monkeys jumping on the bed";
var compareTitle = "5 , monkeys";
/* ^^^
It is very important to separate each word with space-comma-space */
function getWords(str){ //returns an array containing key words
return str.split(" , ");
}
function matches(str, words){
var patt = "";
for (var i = 0; i < words.length; i++){
patt = (i > 0)? patt + "|" + "(" + words[i] + ")" : patt + "(" + words[i] + ")";
}
patt[patt.length-1] = "";
patt = new RegExp(patt, 'gi');
// ^ i makes it case-insensitive
return str.match(patt);
}
matches(compareTitle, getWords(checkTitle)); // should return ['5','monkeys']
you can check if a match exists by doing this:
if (matches(compareTitle, getWords(checkTitle))){
// matches found
}
If this answer is better than the first, accept this one instead. Ask for any more help, or if it doesn't work.

Live replacement for regular expressions with Javascript

I'm writing a code for live replacement of specific words in a text field as the user types.
I'm using regex and javascript:
The first array has the regular expressions to be found, and the second array has the words that should replace any them.
source = new Array(/\srsrs\s/,/\sñ\s/,/\snaum\s/,/\svc\s/,/\scd\s/,/\sOq\s/,/\soke\s/,/\so\sq\s/,
/\soque\s/,/\soqe\s/,/\spq\s/,/\sq\s/,/\sp\/\s/g,/\spra\s/,/\sp\s/,/\stbm\s/,
/\stb\s/,/\std\s/,/\sblz\s/,/\saki\s/,/\svlw\s/,/\smara\s/,/\sqlq\s/,/\sqq\s/,
/\srpz\s/,/\smsm\s/,/\smto\s/,/\smtu\s/,/\sqro\s/,/\sqdo\s/,/\sqd\s/,/\sqnd\s/,
/\sqto\s/,/\sqm\s/,/\sjah\s/, /\sc\/\s/,/\scmg\s/,/\s\+\sou\s\-\s/,/\sflw\s/,
/\sxau\s/,/\sto\s/,/\sta\s/);
after = new Array("risos","não","não","você","cadê","o que","o que","o que","o que","o que","porque",
"que","para","para","para","também","também","tudo","beleza","aqui","valeu","maravilhoso",
"qualquer","qualquer","rapaz","mesmo","muito","muito","quero","quando","quando","quando",
"quanto","quem","Já","com","comego","mais ou menos","falow","tchau","estou","está");
This is the function that does the replacement:
function replacement(){
for(i=0; i<source.length; i++){
newtext = " "+document.getElementById("translation").value+" ";
console.log(newtext);
if(myregex = newtext.match(source[i])){
newafter = after[i];
rafael = myregex+" ";
document.getElementById("translation").value = document.getElementById("translation").value.replace(rafael, newafter);
}
}
}
My problem is every time the function is called to replace an expression with only one letter, the replacement is being made on the first occurrence of that letter, even within a word. I thought looking for that letter with \s before and after would solve it, but it didn't.
If you're looking only to match a word, you should put \b before and after (word boundary). This will ensure that you don't match parts of words. Also note that you are corrupting your regex by concatenating a string. Try this instead:
var in = document.getElementById("translation").value;
if( in.charAt(in.length-1) == " ") { // user has just finished typing a word
// this avoids interrupting the word being typed
var l = source.length, i;
for( i=0; i<l; i++) in = in.replace(source[i],after[i]);
document.getElementById("translation").value = in;
}
You need to add a g (global) modified to regexes so that it will replace all occurrences and use \b instead of \s to mark word boundaries.
source = new Array(/\brsrs\b/g,/\bñ\b/g, etc
On a side note, since all your regexes follow the same pattern it might be easier to just do:
source = new Array( 'rsr', 'ñ', 'naum', etc );
if( myregex = newtext.match( new Regexp( "\b"+source[i]+"\b", 'g' ) ) ) {
...
If by "live replacement" you mean calling function replacement at each keystroke then \b at the end will not help you, you should indeed use \s. However in your replacement function your are adding a space to the text field value so your single character words are triggering the replacement.
Here is my refactoring of your code :
(function () { // wrap in immediate function to hide local variables
source = [ [/\brsrs\s$/, "risos"], // place reg exp and replacement next to each other
[/\b(ñ|naum)\s$/, "não"], // note combined regexps
[/\bvc\s$/, "você"]
// ...
]; // not also use of array literals in place of new Array
document.getElementById ("translation"​​​​​​​).addEventListener ('keyup', function (ev) {
var t = this.value // fetch text area value
, m
, i = source.length;
while (i--) // for each possible match
if ((m = t.match(source[i][0]))) { // does this one match ?
// replace match : first remove the match string (m[0]) from the end of
// the text string, then add the replacement word followed by a space
this.value = t.slice (0, -m[0].length) + source[i][1] + ' ';
return; // done
}
}, false);
}) ();​
And the fiddle is : http://jsfiddle.net/jFYuV
In a somewhat different style, you could create a function that encapsulated the list of substitutions:
var substitutions = {
"rsrs": "risos",
"ñ": "não",
"naum": "não",
"vc": "você",
// ...
};
var createSubstitutionFunction = function(subs) {
var keys = [];
for (var key in subs) {
if (subs.hasOwnProperty(key)) {
keys[keys.length] = key;
}
}
var regex = new RegExp("\\b" + keys.join("\\b|\\b") + "\\b", "g");
return function(text) {
return text.replace(regex, function(match) {
return subs[match];
});
};
};
var replacer = createSubstitutionFunction(substitutions);
You would use it like this:
replacer("Some text with rsrs and naum and more rsrs and vc")
// ==> "Some text with risos and não and more risos and você"

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

I want to use str_replace or its similar alternative to replace some text in JavaScript.
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);
should give
this is some sample text that i dont want to replace
If you are going to regex, what are the performance implications in
comparison to the built in replacement methods.
You would use the replace method:
text = text.replace('old', 'new');
The first argument is what you're looking for, obviously. It can also accept regular expressions.
Just remember that it does not change the original string. It only returns the new value.
More simply:
city_name=city_name.replace(/ /gi,'_');
Replaces all spaces with '_'!
All these methods don't modify original value, returns new strings.
var city_name = 'Some text with spaces';
Replaces 1st space with _
city_name.replace(' ', '_'); // Returns: "Some_text with spaces" (replaced only 1st match)
Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/
city_name.replace(/ /gi,'_'); // Returns: Some_text_with_spaces
Replaces all spaces with _ without regex. Functional way.
city_name.split(' ').join('_'); // Returns: Some_text_with_spaces
You should write something like that :
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like #sorgit said). To replace all the "want" with "not want", us this code:
var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);
The variable "new_text" will result in being "this is some sample text that i dont want to replace".
To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about str.replace(), go here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!
that function replaces only one occurrence.. if you need to replace
multiple occurrences you should try this function:
http://phpjs.org/functions/str_replace:527
Not necessarily.
see the Hans Kesting answer:
city_name = city_name.replace(/ /gi,'_');
Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:
Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.
For a simple test run on the JS perf page, I've documented some of the results:
<script>
// Setup
var startString = "xxxxxxxxxabcxxxxxxabcxx";
var endStringRegEx = undefined;
var endStringString = undefined;
var endStringRegExNewStr = undefined;
var endStringRegExNew = undefined;
var endStringStoredRegEx = undefined;
var re = new RegExp("abc", "g");
</script>
<script>
// Tests
endStringRegEx = startString.replace(/abc/g, "def") // Regex
endStringString = startString.replace("abc", "def", "g") // String
endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
endStringStoredRegEx = startString.replace(re, "def") // saved regex
</script>
The results for Chrome 68 are as follows:
String replace: 9,936,093 operations/sec
Saved regex: 5,725,506 operations/sec
Regex: 5,529,504 operations/sec
New Regex String: 3,571,180 operations/sec
New Regex: 3,224,919 operations/sec
From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace only replaces the first instance of the matched character. Its only possible to replace all instances with //g. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }
var new_text = text.replace("want", "dont want");
hm.. Did you check replace() ?
Your code will look like this
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace() method having both string arguments is shown below.
var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text) //ten, two, three, one, five, one
Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g (global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one in the above example.
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text) //ten, two, three, ten, five, ten
Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi. Notice the i flag added here.
If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten
You can have more control over the replacement text using a function as the second argument.
In JavaScript, you call the replace method on the String object, e.g. "this is some sample text that i want to replace".replace("want", "dont want"), which will return the replaced string.
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched
You can use
text.replace('old', 'new')
And to change multiple values in one string at once, for example to change # to string v and _ to string w:
text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});
There are already multiple answers using str.replace() (which is fair enough for this question) and regex but you can use combination of str.split() and join() together which is faster than str.replace() and regex.
Below is working example:
var text = "this is some sample text that i want to replace";
console.log(text.split("want").join("dont want"));
If you really want a equivalent to PHP's str_replace you can use Locutus. PHP's version of str_replace support more option then what the JavaScript String.prototype.replace supports.
For example tags:
//PHP
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
//JS with Locutus
var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')
or array's
//PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
//JS with Locutus
var $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
var $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on Locutus )
function str_replace (search, replace, subject) {
var i = 0
var j = 0
var temp = ''
var repl = ''
var sl = 0
var fl = 0
var f = [].concat(search)
var r = [].concat(replace)
var s = subject
s = [].concat(s)
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + ''
repl = r[0]
s[i] = (temp).split(f[j]).join(repl)
if (typeof countObj !== 'undefined') {
countObj.value += ((temp.split(f[j])).length - 1)
}
}
}
return s[0]
}
var text = "this is some sample text that i want to replace";
var new_text = str_replace ("want", "dont want", text)
document.write(new_text)
for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js
You have the following options:
Replace the first occurrence
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace('want', 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"
console.log(new_text)
Replace all occurrences - case sensitive
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/g, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well
console.log(new_text)
Replace all occurrences - case insensitive
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/gi, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well
console.log(new_text)
More info -> here
In Javascript, replace function available to replace sub-string from given string with new one.
Use:
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
console.log(new_text);
You can even use regular expression with this function. For example, if want to replace all occurrences of , with ..
var text = "123,123,123";
var new_text = text.replace(/,/g, ".");
console.log(new_text);
Here g modifier used to match globally all available matches.
Method to replace substring in a sentence using React:
const replace_in_javascript = (oldSubStr, newSubStr, sentence) => {
let newStr = "";
let i = 0;
sentence.split(" ").forEach(obj => {
if (obj.toUpperCase() === oldSubStr.toUpperCase()) {
newStr = i === 0 ? newSubStr : newStr + " " + newSubStr;
i = i + 1;
} else {
newStr = i === 0 ? obj : newStr + " " + obj;
i = i + 1;
}
});
return newStr;
};
RunMethodHere
If you don't want to use regex then you can use this function which will replace all in a string
Source Code:
function ReplaceAll(mystring, search_word, replace_with)
{
while (mystring.includes(search_word))
{
mystring = mystring.replace(search_word, replace_with);
}
return mystring;
}
How to use:
var mystring = ReplaceAll("Test Test", "Test", "Hello");
Use JS String.prototype.replace first argument should be Regex pattern or String and Second argument should be a String or function.
str.replace(regexp|substr, newSubStr|function);
Ex:
var str = 'this is some sample text that i want to replace';
var newstr = str.replace(/want/i, "dont't want");
document.write(newstr); // this is some sample text that i don't want to replace
ES2021 / ES12
String.prototype.replaceAll()
is trying to bring the full replacement option even when the input pattern is a string.
const str = "Backbencher sits at the Back";
const newStr = str.replaceAll("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Front"
1- String.prototype.replace()
We can do a full **replacement** only if we supply the pattern as a regular expression.
const str = "Backbencher sits at the Back";
const newStr = str.replace(/Back/g, "Front");
console.log(newStr); // "Frontbencher sits at the Front"
If the input pattern is a string, replace() method only replaces the first occurrence.
const str = "Backbencher sits at the Back";
const newStr = str.replace("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Back"
2- You can use split and join
const str = "Backbencher sits at the Back";
const newStr = str.split("Back").join("Front");
console.log(newStr); // "Frontbencher sits at the Front"
function str_replace($old, $new, $text)
{
return ($text+"").split($old).join($new);
}
You do not need additional libraries.
In ECMAScript 2021, you can use replaceAll can be used.
const str = "string1 string1 string1"
const newStr = str.replaceAll("string1", "string2");
console.log(newStr)
// "string2 string2 string2"
simplest form as below
if you need to replace only first occurrence
var newString = oldStr.replace('want', 'dont want');
if you want ot repalce all occurenace
var newString = oldStr.replace(want/g, 'dont want');
Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable new_text.
let replace_in_javascript= (replaceble, replaceTo, text) => {
return text.replace(replaceble, replaceTo)
}
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);

Categories

Resources