How make lodash _.replace all occurrence in a string? - javascript

How to replace each occurrence of a string pattern in a string by another string?
var text = "azertyazerty";
_.replace(text,"az","qu")
return quertyazerty

You can also do
var text = "azertyazerty";
var result = _.replace(text, /az/g, "qu");

you have to use the RegExp with global option offered by lodash.
so just use
var text = "azertyazerty";
_.replace(text,new RegExp("az","g"),"qu")
to return quertyquerty

I love lodash, but this is probably one of the few things that is easier without it.
var str = str.split(searchStr).join(replaceStr)
As a utility function with some error checking:
var replaceAll = function (str, search, replacement) {
var newStr = ''
if (_.isString(str)) { // maybe add a lodash test? Will not handle numbers now.
newStr = str.split(search).join(replacement)
}
return newStr
}
For completeness, if you do really really want to use lodash, then to actually replace the text, assign the result to the variable.
var text = 'find me find me find me'
text = _.replace(text,new RegExp('find','g'),'replace')
References:
How to replace all occurrences of a string in JavaScript?

Vanilla JS is fully capable of doing what you need without the help of lodash.
const text = "azertyazerty"
text.replace(new RegExp("az", "g"), "qu")

Related

Javascript: split a string according to two criteria?

I am trying to count the number of sentences in a paragraph. In the paragraph, all sentences end with either ''.'' or ''!''.
My idea is to first split the paragraph into strings whenever there's a ''.'' or ''!'' and then count the number of splitted strings.
I have tried
.split('.' || '!')
but that does not work. It only splits strings whenever there is a ''.''
May I know how to deal with this?
Just use a Regexp, it's pretty simple ;)
const example = 'Hello! You should probably use a regexp. Nice isn\'t it?';
console.log(example.split(/[.!]/));
You will need to use a regex for this.
The following should work:
.split(/\.|!/)
You can use regex /\.|!/ in split() as str.split(/\.|!/) :
var str = 'some.string';
console.log(str.split(/\.|!/));
str = 'some.string!name';
console.log(str.split(/\.|!/));
const sampleString = 'I am handsome. Are you sure?! Just kidding. Thank you.';
const result = sampleString.split(/\.|!/)
console.log(result);
// to remove elements that has no value you can do
const noEmptyElements = result.filter(str => str);
console.log(noEmptyElements);
Try below code it will give you an exact count of sentences in the paragraph.
function count(string,char) {
var re = new RegExp(char,"gi");
return string.match(re).length;
}
function myFunction() {
var str = 'but that! does! not work. It only splits strings whenever there is a. ';
console.log(count(str,'[.?!]'));
}

Cant make regex work to remove the first white space character

I have the following div:
<div data-test="([1] Hello World), ([2] Foo Bar)"></div>
Now what I am trying to do is to find the cleanest way to break the string into the following pieces:
array ["1", "Hello World", "2", "Foo Bar"];
How can I achieve this the proper and fast way?
I managed to get close but my solution seems somewhat ugly and doesnt work as expected.
var el = document.getElementsByTagName("div")[0];
data = el.getAttribute('data-test');
list = data.replace(/[([,]/g, '').split(/[\]\)]/);
for(str of list) {
str = str.trim();
}
I still get the spaces at the start of each string. I dont really want to use trim or anything similar. I tried to add a whitespace character to my regex s/ but that was a bad idea too.
The below function should work.
function strToArr(str) {
var arr = [];
var parts = str.split(', ');
parts.forEach(part => {
var digit = part.match(/(\d+)/g)[0];
var string = part.match(/(\b[a-zA-Z\s]+)/g)[0];
arr.push(digit, string);
});
return arr;
}
var text = '([1] Hello World), ([2] Foo Bar)';
var textReplaced = text.replace(/\(\[([^\]])\]\s([^)]+)\)/g, '$1, $2');
var array = textReplaced.split(', ');
console.log(array);
Without any cycle.
You can try the following regular expression:
list = data.replace(/^\(\[|\)$/g, '').split(/\] |\), \(\[|\] /);
Two steps:
remove the heading "(["and tailing ")"
split the string into the parts you want with the delimiter symbols
Suppose the format of the string is fixed.

javascript split with regex

I would like to split characters into array using javascript with regex
foo=foobar=&foobar1=foobar2=
into
foo, foobar=,
foobar1, foobar2=
Sorry for not being clear, let me re describe the scenario.
First i would split it by "&" and want to post process it later.
str=foo=foobar=&foobar1=foobar2=
var inputvars=str.split("&")
for(i=0;i<inputvars.length;i++){
var param = inputvars[i].split("=");
console.log(param);
}
returns
[foo,foobar]
[]
[foobar1=foobar2]
[]
I tried to use .split("=") but foobar= got splited out as foobar.
I essentially want it to be
[foo,foobar=]
[foobar1,foobar2=]
Any help with using javascript to split first occurence of = only?
/^([^=]*)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
or simpler to write but using the newer "lazy" operator:
/(.*?)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
from malvolio, i got to conclusion below
var str = 'foo=foobar=&foobar1=foobar2=';
var inputvars = str.split("&");
var pattern = /^([^=]*)=(.*)/;
for (counter=0; counter<inputvars.length; counter++){
var param = pattern.exec(inputvars[counter]);
console.log(param)
}
and results (which is what i intended)
[foo,foobar=]
[foobar1,foobar2=]
Thanks to #malvolio hint of regex
Cheers

Removing string using javascript

I have a string like
var test="ALL,l,1,2,3";
How to remove ALL from string if it contains using javascript.
Regards,
Raj
you can use js replace() function:
http://www.w3schools.com/jsref/jsref_replace.asp
so:
test.replace("ALL,", "");
If the word All can appear anywhere or more than once (e.g. "l,1,ALL,2,3,ALL") then have such code:
var test = "l,1,ALL,2,3,ALL"
var parts = test.split(",");
var clean = [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part !== "ALL")
clean.push(part);
}
var newTest = clean.join(",");
After this the variable newTest will hold the string without ALL.
If all you want to do is remove occurrences of the string "ALL" from another string, you can use the JavaScript String object's replace method:
test.replace("ALL","");
I'm not really sure if you want to remove all instances of capital letters from your string, but you are probably looking at using a regular expression such as s.replace(/[A-Z]/g,"") where s is the string.
Looking up javascript RegExp will give more indepth details.
use:
test.replace ( 'ALL,', '' );

In Javascript, how can I perform a global replace on string with a variable inside '/' and '/g'?

I want to perform a global replace of string using String.replace in Javascript.
In the documentation I read that I can do this with /g, i.e. for example;
var mystring = mystring.replace(/test/g, mystring);
and this will replace all occurrences inside mystring. No quotes for the expression.
But if I have a variable to find, how can I do this without quotes?
I've tried something like this:
var stringToFind = "test";
//first try
mystring = mystring.replace('/' + stringToFind + '/g', mystring);
//second try, not much sense at all
mystring = mystring.replace(/stringToFind/g, mystring);
but they don't work. Any ideas?
var mystring = "hello world test world";
var find = "world";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay"
In case you need this into a function
replaceGlobally(original, searchTxt, replaceTxt) {
const regex = new RegExp(searchTxt, 'g');
return original.replace(regex, replaceTxt) ;
}
For regex, new RegExp(stringtofind, 'g');. BUT. If ‘find’ contains characters that are special in regex, they will have their regexy meaning. So if you tried to replace the '.' in 'abc.def' with 'x', you'd get 'xxxxxxx' — whoops.
If all you want is a simple string replacement, there is no need for regular expressions! Here is the plain string replace idiom:
mystring= mystring.split(stringtofind).join(replacementstring);
Regular expressions are much slower then string search. So, creating regex with escaped search string is not an optimal way. Even looping though the string would be faster, but I suggest using built-in pre-compiled methods.
Here is a fast and clean way of doing fast global string replace:
sMyString.split(sSearch).join(sReplace);
And that's it.
String.prototype.replaceAll = function (replaceThis, withThis) {
var re = new RegExp(RegExp.quote(replaceThis),"g");
return this.replace(re, withThis);
};
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};
var aa = "qwerr.erer".replaceAll(".","A");
alert(aa);
silmiar post
You can use the following solution to perform a global replace on a string with a variable inside '/' and '/g':
myString.replace(new RegExp(strFind, 'g'), strReplace);
Thats a regular expression, not a string. Use the constructor for a RegExp object to dynamically create a regex.
var r = new RegExp(stringToFind, 'g');
mystring.replace(r, 'some replacement text');
Try:
var stringToFind = "test";
mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring);
You can do using following method
see this function:
function SetValue()
{
var txt1='This is a blacK table with BLack pen with bLack lady';
alert(txt1);
var txt2= txt1.replace(/black/gi,'green');
alert(txt2);
}
syntax:
/search_string/{g|gi}
where
g is global case-sensitive replacement
gi is blobal case-insensitive replacement
You can check this JSBIN link
http://jsbin.com/nohuroboxa/edit?html,js,output
If you want variables interpolated, you need to use the RegExp object
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions
Example:
var str = "This is my name";
var replace = "i";
var re = new RegExp(replace, 'g')
str = str.replace(re, 'p');
alert(str);
Dynamic global replace
I came to this thread looking for a slightly more complex solution which isn't answered here. I've now found the answer so I'm going to post it in case anyone else finds it useful.
I wanted to do a dynamic global replace, where the replacement strings are based on the original matches.
For example, to capitalise the first letter of all words (e.g. "cat sat mat" into "Cat Sat Mat") with a global find replace. Here's how to do that.
function capitaliseWords(aString) {
// Global match for lowercase letters following a word boundary
var letters = aString.match(/\b[a-z]/g), i, letterMatch;
// Loop over all matched letters
for( i = 0; i < letters.length; i++ ) {
// Replace the matched letters with upper case versions
letterMatch = new RegExp('\\b'+letters[i]); // EDIT - slight fix
aString = aString.replace(letterMatch, letters[i].toUpperCase());
}
// Return our newly capitalised string
return aString;
}
alert( capitaliseWords("cat sat mat") ); // Alerts "Cat Sat Mat"
WIth modern day linters, they prefer you to regEx literal, so rather than new RegExp it would just be `//
With an example:
'test'.replace(/ /gi, '_')
with the test you are looking to replace inside the regex or the /searchableText/ and then replace text in the second parameter. In my case I wanted to replace all spaces with underscores.
Can you use prototype.js? If so you could use String.gsub, like
var myStr = "a day in a life of a thing";
var replace = "a";
var resultString = myStr.gsub(replace, "g");
// resultString will be "g day in g life of g thing"
It will also take regular expressions. To me this is one of the more elegant ways to solve it. prototypejs gsub documentation

Categories