Template and Place holders algorithm - javascript

First a quick definition :)
Template - A string which may contain placeholders (example:"hello [name]")
Placeholder - A substring whitin square brackets (example: "name" in "hello [name]:).
Properties map - A valid object with strings as values
I need to write a code that replace placeholders (along with brackets) with the matching values in the properties map.
example:
for the following properties map:
{
"name":"world",
"my":"beautiful",
"a":"[b]",
"b":"c",
"c":"my"
}
Expected results:
"hello name" -> "hello name"
"hello [name]" -> "hello world"
"[b]" -> "c"
"[a]" -> "c" (because [a]->[b]->[c])
"[[b]]" -> "my" (because [[b]]->[c]->my)
"hello [my] [name]" -> "hello beautiful world"

var map = {
"name":"world",
"my":"beautiful",
"a":"[b]",
"b":"c",
"c":"my"
};
var str = "hello [my] [name] [[b]]";
do {
var strBeforeReplace = str;
for (var k in map) {
if (!map.hasOwnProperty(k)) continue;
var needle = "[" + k + "]";
str = str.replace(needle, map[k]);
}
var strChanged = str !== strBeforeReplace;
} while (strChanged);
document.write(str); //hello beautiful world my

The answer by #chris is excellent, I just want to provide an alternative solution using regular expressions that works "the other way round", i.e., not by looking for occurrences of the "placeholder versions" of all items in the properties map, but by repeatedly looking for occurrences of the placeholder itself, and substituting it with the corresponding value from the property map. This has two advantages:
If the property map grows very large, this solution should have
better performance (still to be benchmarked though).
The placeholder and the way substitutions work can easily be modified by adjusting the regular expression and the substitution function (might not be an issue here).
The downside is, of course, that the code is a little more complex (partly due to the fact that JavaScript lacks a nice way of substituting regular expression matches using custom functions, so that's what substituteRegExp is for):
function substituteRegExp(string, regexp, f) {
// substitute all matches of regexp in string with the value
// returned by f given a match and the corresponding group values
var found;
var lastIndex = 0;
var result = "";
while (found = regexp.exec(string)) {
var subst = f.apply(this, found);
result += string.slice(lastIndex, found.index) + subst;
lastIndex = found.index + found[0].length;
}
result += string.slice(lastIndex);
return result;
}
function templateReplace(string, values) {
// repeatedly substitute [key] placeholders in string by values[key]
var placeholder = /\[([a-zA-Z0-9]+)\]/g;
while (true) {
var newString = substituteRegExp(string, placeholder, function(match, key) {
return values[key];
});
if (newString == string)
break;
string = newString;
}
return string;
}
alert(templateReplace("hello [[b]] [my] [name]", {
"name":"world",
"my":"beautiful",
"a":"[b]",
"b":"c",
"c":"my"
})); // -> "hello my beautiful world"
Update: I did some little profiling to compare the two solutions (jsFiddle at http://jsfiddle.net/n8Fyv/1/, I also used Firebug). While #chris' solution is faster for small strings (no need for parsing the regular expression etc), this solution performs a lot better for large strings (in the order of thousands of characters). I did not compare for different sizes of the property map, but expect even bigger differences there.
In theory, this solution has runtime O(k n) where k is the depth of nesting of placeholders and n is the length of the string (assuming dictionary/hash lookups need constant time), while #chris' solution is O(k n m) where m is the number of items in the property map. All of this is only relevant for large inputs, of course.

If you're familiar with .NET's String.Format, then you should take a look at this JavaScript implementation. It supports number formatting too, just like String.Format.
Here's an example of how to use it:
var result = String.Format("Hello {my} {name}", map);
However, it would require some modification to do recursive templates.

Related

Remove item from array containing text [duplicate]

I need to search an array in JavaScript. The search would be for only part of the string to match as the string would have additional components. I would then need to return the successfully matched array element with the full string.
Example:
const windowArray = [ "item", "thing", "id-3-text", "class" ];
I need to search for the array element with "id-" in it and I need to pull the rest of the text in the element as well (i.e. "id-3-text").
How do I do that?
If you're able to use Underscore.js in your project, the _.filter() array function makes this a snap:
// find all strings in array containing 'thi'
var matches = _.filter(
[ 'item 1', 'thing', 'id-3-text', 'class' ],
function( s ) { return s.indexOf( 'thi' ) !== -1; }
);
The iterator function can do whatever you want as long as it returns true for matches. Works great.
Update 2017-12-03:
This is a pretty outdated answer now. Maybe not the most performant option in a large batch, but it can be written a lot more tersely and use native ES6 Array/String methods like .filter() and .includes() now:
// find all strings in array containing 'thi'
const items = ['item 1', 'thing', 'id-3-text', 'class'];
const matches = items.filter(s => s.includes('thi'));
Note: There's no <= IE11 support for String.prototype.includes() (Edge works, mind you), but you're fine with a polyfill, or just fall back to indexOf().
People here are making this waaay too difficult. Just do the following...
myArray.findIndex(element => element.includes("substring"))
findIndex() is an ES6 higher order method that iterates through the elements of an array and returns the index of the first element that matches some criteria (provided as a function). In this case I used ES6 syntax to declare the higher order function. element is the parameter of the function (which could be any name) and the fat arrow declares what follows as an anonymous function (which does not need to be wrapped in curly braces unless it takes up more than one line).
Within findIndex() I used the very simple includes() method to check if the current element includes the substring that you want.
The simplest way to get the substrings array from the given array is to use filter and includes:
myArray.filter(element => element.includes("substring"));
The above one will return an array of substrings.
myArray.find(element => element.includes("substring"));
The above one will return the first result element from the array.
myArray.findIndex(element => element.includes("substring"));
The above one will return the index of the first result element from the array.
In your specific case, you can do it just with a boring old counter:
var index, value, result;
for (index = 0; index < windowArray.length; ++index) {
value = windowArray[index];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
// Use `result` here, it will be `undefined` if not found
But if your array is sparse, you can do it more efficiently with a properly-designed for..in loop:
var key, value, result;
for (key in windowArray) {
if (windowArray.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
value = windowArray[key];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
}
// Use `result` here, it will be `undefined` if not found
Beware naive for..in loops that don't have the hasOwnProperty and !isNaN(parseInt(key, 10)) checks; here's why.
Off-topic:
Another way to write
var windowArray = new Array ("item","thing","id-3-text","class");
is
var windowArray = ["item","thing","id-3-text","class"];
...which is less typing for you, and perhaps (this bit is subjective) a bit more easily read. The two statements have exactly the same result: A new array with those contents.
Just search for the string in plain old indexOf
arr.forEach(function(a){
if (typeof(a) == 'string' && a.indexOf('curl')>-1) {
console.log(a);
}
});
The simplest vanilla javascript code to achieve this is
var windowArray = ["item", "thing", "id-3-text", "class", "3-id-text"];
var textToFind = "id-";
//if you only want to match id- as prefix
var matches = windowArray.filter(function(windowValue){
if(windowValue) {
return (windowValue.substring(0, textToFind.length) === textToFind);
}
}); //["id-3-text"]
//if you want to match id- string exists at any position
var matches = windowArray.filter(function(windowValue){
if(windowValue) {
return windowValue.indexOf(textToFind) >= 0;
}
}); //["id-3-text", "3-id-text"]
For a fascinating examination of some of the alternatives and their efficiency, see John Resig's recent posts:
JavaScript Trie Performance Analysis
Revised JavaScript Dictionary Search
(The problem discussed there is slightly different, with the haystack elements being prefixes of the needle and not the other way around, but most solutions are easy to adapt.)
let url = item.product_image_urls.filter(arr=>arr.match("homepage")!==null)
Filter array with string match. It is easy and one line code.
ref:
In javascript, how do you search an array for a substring match
The solution given here is generic unlike the solution 4556343#4556343, which requires a previous parse to identify a string with which to join(), that is not a component of any of the array strings.
Also, in that code /!id-[^!]*/ is more correctly, /![^!]*id-[^!]*/ to suit the question parameters:
"search an array ..." (of strings or numbers and not functions, arrays, objects, etc.)
"for only part of the string to match " (match can be anywhere)
"return the ... matched ... element" (singular, not ALL, as in "... the ... elementS")
"with the full string" (include the quotes)
... NetScape / FireFox solutions (see below for a JSON solution):
javascript: /* "one-liner" statement solution */
alert(
["x'!x'\"id-2",'\' "id-1 "', "item","thing","id-3-text","class" ] .
toSource() . match( new RegExp(
'[^\\\\]("([^"]|\\\\")*' + 'id-' + '([^"]|\\\\")*[^\\\\]")' ) ) [1]
);
or
javascript:
ID = 'id-' ;
QS = '([^"]|\\\\")*' ; /* only strings with escaped double quotes */
RE = '[^\\\\]("' +QS+ ID +QS+ '[^\\\\]")' ;/* escaper of escaper of escaper */
RE = new RegExp( RE ) ;
RA = ["x'!x'\"id-2",'\' "id-1 "', "item","thing","id-3-text","class" ] ;
alert(RA.toSource().match(RE)[1]) ;
displays "x'!x'\"id-2".
Perhaps raiding the array to find ALL matches is 'cleaner'.
/* literally (? backslash star escape quotes it!) not true, it has this one v */
javascript: /* purely functional - it has no ... =! */
RA = ["x'!x'\"id-2",'\' "id-1 "', "item","thing","id-3-text","class" ] ;
function findInRA(ra,id){
ra.unshift(void 0) ; /* cheat the [" */
return ra . toSource() . match( new RegExp(
'[^\\\\]"' + '([^"]|\\\\")*' + id + '([^"]|\\\\")*' + '[^\\\\]"' ,
'g' ) ) ;
}
alert( findInRA( RA, 'id-' ) . join('\n\n') ) ;
displays:
"x'!x'\"id-2"
"' \"id-1 \""
"id-3-text"
Using, JSON.stringify():
javascript: /* needs prefix cleaning */
RA = ["x'!x'\"id-2",'\' "id-1 "', "item","thing","id-3-text","class" ] ;
function findInRA(ra,id){
return JSON.stringify( ra ) . match( new RegExp(
'[^\\\\]"([^"]|\\\\")*' + id + '([^"]|\\\\")*[^\\\\]"' ,
'g' ) ) ;
}
alert( findInRA( RA, 'id-' ) . join('\n\n') ) ;
displays:
["x'!x'\"id-2"
,"' \"id-1 \""
,"id-3-text"
wrinkles:
The "unescaped" global RegExp is /[^\]"([^"]|\")*id-([^"]|\")*[^\]"/g with the \ to be found literally. In order for ([^"]|\")* to match strings with all "'s escaped as \", the \ itself must be escaped as ([^"]|\\")*. When this is referenced as a string to be concatenated with id-, each \ must again be escaped, hence ([^"]|\\\\")*!
A search ID that has a \, *, ", ..., must also be escaped via .toSource() or JSON or ... .
null search results should return '' (or "" as in an EMPTY string which contains NO "!) or [] (for all search).
If the search results are to be incorporated into the program code for further processing, then eval() is necessary, like eval('['+findInRA(RA,ID).join(',')+']').
--------------------------------------------------------------------------------
Digression:
Raids and escapes? Is this code conflicted?
The semiotics, syntax and semantics of /* it has no ... =! */ emphatically elucidates the escaping of quoted literals conflict.
Does "no =" mean:
"no '=' sign" as in javascript:alert('\x3D') (Not! Run it and see that there is!),
"no javascript statement with the assignment operator",
"no equal" as in "nothing identical in any other code" (previous code solutions demonstrate there are functional equivalents),
...
Quoting on another level can also be done with the immediate mode javascript protocol URI's below. (// commentaries end on a new line (aka nl, ctrl-J, LineFeed, ASCII decimal 10, octal 12, hex A) which requires quoting since inserting a nl, by pressing the Return key, invokes the URI.)
javascript:/* a comment */ alert('visible') ;
javascript:// a comment ; alert( 'not' ) this is all comment %0A;
javascript:// a comment %0A alert('visible but %\0A is wrong ') // X %0A
javascript:// a comment %0A alert('visible but %'+'0A is a pain to type') ;
Note: Cut and paste any of the javascript: lines as an immediate mode URI (at least, at most?, in FireFox) to use first javascript: as a URI scheme or protocol and the rest as JS labels.
I've created a simple to use library (ss-search) which is designed to handle objects, but could also work in your case:
search(windowArray.map(x => ({ key: x }), ["key"], "SEARCH_TEXT").map(x => x.key)
The advantage of using this search function is that it will normalize the text before executing the search to return more accurate results.
Another possibility is
var res = /!id-[^!]*/.exec("!"+windowArray.join("!"));
return res && res[0].substr(1);
that IMO may make sense if you can have a special char delimiter (here i used "!"), the array is constant or mostly constant (so the join can be computed once or rarely) and the full string isn't much longer than the prefix searched for.
I think this may help you. I had a similar issue. If your array looks like this:
var array = ["page1","1973","Jimmy"];
You can do a simple "for" loop to return the instance in the array when you get a match.
var c;
for (i = 0; i < array.length; i++) {
if (array[i].indexOf("page") > -1){
c = i;}
}
We create an empty variable, c to host our answer.
We then loop through the array to find where the array object (e.g. "page1") matches our indexOf("page"). In this case, it's 0 (the first result)
Happy to expand if you need further support.
Use this function for search substring Item.
function checkItem(arrayItem, searchItem) {
return arrayItem.findIndex(element => element.includes(searchItem)) >= 0
}
function getItem(arrayItem, getItem) {
return arrayItem.filter(element => element.includes(getItem))
}
var arrayItem = ["item","thing","id-3-text","class"];
console.log(checkItem(arrayItem, "id-"))
console.log(checkItem(arrayItem, "vivek"))
console.log(getItem(arrayItem, "id-"))
Here's your expected snippet which gives you the array of all the matched values:
var windowArray = new Array ("item","thing","id-3-text","class");
var result = [];
windowArray.forEach(val => {
if(val && val.includes('id-')) {
result.push(val);
}
});
console.log(result);
this worked for me .
const filterData = this.state.data2.filter(item=>((item.name.includes(text)) || (item.surname.includes(text)) || (item.email.includes(text)) || (item.userId === Number(text))) ) ;

how to get list of unique chars from a string in javascript?

I have some text files, each with a mix of western and chinese characters. I want a list of the chinese characters that appear in each file.
I have tried
ch = text.match(/[\u4E00-\u9FFF]/g); // unicode usual chinese characters - that'll do for me
if (ch != null) {
alert(ch);
}
This gives me the list of chinese characters, but with some repetitions. For example:
肉,捕,兵,死,兵,半,水
for a file
卵,水,半,水,土,木,水,清,慢,底,海,海,海,清,清,清,木,清,慢,底,清,土,半,水,水,土,半,水,土
for another...
1) I don't need those commas. Where did they come from? (I can take them off with a single replace, but since I'm using regex, I think it may be faster if I solve it inside the regex itself.)
2) How to get only unique values? For example:
肉捕兵死半水
for the first file
卵水半土木清慢底海
for the second...
commas come from default array to string conversion. use ch.join('') to convert array to string instead.
To remove duplicate values, use this line:
ch = text.match(/([\u4E00-\u9FFF])/g);
ch = ch.filter(function (c, i) { return ch.indexOf(c) === i; }).join('');
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
ch = text.match(/([\u4E00-\u9FFF])/g);
var result_string = ch.getUnique().join("");
Try this:
var text = "卵水半水土木水清慢底海海海清清清木清慢底清土半水水土半水土",
re = /([\u4E00-\u9FFF])/g,
unique = {},
chars = "", c;
while(c = re.exec(text)){
if(!unique[c[0]]){
chars += c[0];
unique[c[0]] = true;
}
}
chars.split("");
Which returned:
["卵", "水", "半", "土", "木", "清", "慢", "底", "海"]
And yes, the commas you're seeing are when a browser typecasts an array to a string: it joins the the string representations of each value together with commas. I'm guessing that came from the call to "alert" in your original example, which was being supplied an array (returned from the string's "Match" method).
Array's "filter" method isn't supported in legacy browsers, but it's quite easy to polyfill (and certainly not necessary to if you're only concerned with supporting agents as recent as IE9).
There is a one-liner solution with regex:
input.match(/([\u4E00-\u9FFF])(?![\s\S]*\1)/g)
However, I wouldn't recommend using it, since it will have O(n * k) complexity in worst case (when the string contains mostly Chinese characters), where n is the length of the string and k is the number of unique Chinese characters. Why O(n * k)? Since the look-ahead (?![\s\S]*\1) basically says "assert that you can't find another instance of whatever matched in first capturing group in the rest of the string".
This answer by #Ruben Kazumov is a reasonable alternative. Its complexity depends on the implementation of setting and getting property in an Object, which should be sub-linear per operation in a reasonable implementation.

How to use Javascript to change link [duplicate]

I've got a data-123 string.
How can I remove data- from the string while leaving the 123?
var ret = "data-123".replace('data-','');
console.log(ret); //prints: 123
Docs.
For all occurrences to be discarded use:
var ret = "data-123".replace(/data-/g,'');
PS: The replace function returns a new string and leaves the original string unchanged, so use the function return value after the replace() call.
This doesn't have anything to do with jQuery. You can use the JavaScript replace function for this:
var str = "data-123";
str = str.replace("data-", "");
You can also pass a regex to this function. In the following example, it would replace everything except numerics:
str = str.replace(/[^0-9\.]+/g, "");
You can use "data-123".replace('data-','');, as mentioned, but as replace() only replaces the FIRST instance of the matching text, if your string was something like "data-123data-" then
"data-123data-".replace('data-','');
will only replace the first matching text. And your output will be "123data-"
DEMO
So if you want all matches of text to be replaced in string you have to use a regular expression with the g flag like that:
"data-123data-".replace(/data-/g,'');
And your output will be "123"
DEMO2
You can use slice(), if you will know in advance how many characters need slicing off the original string. It returns characters between a given start point to an end point.
string.slice(start, end);
Here are some examples showing how it works:
var mystr = ("data-123").slice(5); // This just defines a start point so the output is "123"
var mystr = ("data-123").slice(5,7); // This defines a start and an end so the output is "12"
Demo
Plain old JavaScript will suffice - jQuery is not necessary for such a simple task:
var myString = "data-123";
var myNewString = myString.replace("data-", "");
See: .replace() docs on MDN for additional information and usage.
1- If is the sequences into your string:
let myString = "mytest-text";
let myNewString = myString.replace("mytest-", "");
the answer is text
2- if you whant to remove the first 3 characters:
"mytest-text".substring(3);
the answer is est-text
Ex:-
var value="Data-123";
var removeData=value.replace("Data-","");
alert(removeData);
Hopefully this will work for you.
Performance
Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.
Results
For all browsers
solutions Ba, Cb, and Db are fast/fastest for long strings
solutions Ca, Da are fast/fastest for short strings
solutions Ab and E are slow for long strings
solutions Ba, Bb and F are slow for short strings
Details
I perform 2 tests cases:
short string - 10 chars - you can run it HERE
long string - 1 000 000 chars - you can run it HERE
Below snippet presents solutions
Aa
Ab
Ba
Bb
Ca
Cb
Da
Db
E
F
// https://stackoverflow.com/questions/10398931/how-to-strToRemove-text-from-a-string
// https://stackoverflow.com/a/10398941/860099
function Aa(str,strToRemove) {
return str.replace(strToRemove,'');
}
// https://stackoverflow.com/a/63362111/860099
function Ab(str,strToRemove) {
return str.replaceAll(strToRemove,'');
}
// https://stackoverflow.com/a/23539019/860099
function Ba(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replace(new RegExp(re),'');
}
// https://stackoverflow.com/a/63362111/860099
function Bb(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replaceAll(new RegExp(re,'g'),'');
}
// https://stackoverflow.com/a/27098801/860099
function Ca(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/27098801/860099
function Cb(str,strToRemove) {
let start = str.search(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/23181792/860099
function Da(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/23181792/860099
function Db(str,strToRemove) {
let start = str.search(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/49857431/860099
function E(str,strToRemove) {
return str.split(strToRemove).join('');
}
// https://stackoverflow.com/a/45406624/860099
function F(str,strToRemove) {
var n = str.search(strToRemove);
while (str.search(strToRemove) > -1) {
n = str.search(strToRemove);
str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length);
}
return str;
}
let str = "data-123";
let strToRemove = "data-";
[Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`${f.name.padEnd(2,' ')} ${f(str,strToRemove)}`));
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
This little function I made has always worked for me :)
String.prototype.deleteWord = function (searchTerm) {
var str = this;
var n = str.search(searchTerm);
while (str.search(searchTerm) > -1) {
n = str.search(searchTerm);
str = str.substring(0, n) + str.substring(n + searchTerm.length, str.length);
}
return str;
}
// Use it like this:
var string = "text is the cool!!";
string.deleteWord('the'); // Returns text is cool!!
I know it is not the best, but It has always worked for me :)
str.split('Yes').join('No');
This will replace all the occurrences of that specific string from original string.
I was used to the C# (Sharp) String.Remove method.
In Javascript, there is no remove function for string, but there is substr function.
You can use the substr function once or twice to remove characters from string.
You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):
function Remove(str, startIndex) {
return str.substr(0, startIndex);
}
and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):
function Remove(str, startIndex, count) {
return str.substr(0, startIndex) + str.substr(startIndex + count);
}
and then you can use these two functions or one of them for your needs!
Example:
alert(Remove("data-123", 0, 5));
Output: 123
Using match() and Number() to return a number variable:
Number(("data-123").match(/\d+$/));
// strNum = 123
Here's what the statement above does...working middle-out:
str.match(/\d+$/) - returns an array containing matches to any length of numbers at the end of str. In this case it returns an array containing a single string item ['123'].
Number() - converts it to a number type. Because the array returned from .match() contains a single element Number() will return the number.
Update 2023
There are many ways to solve this problem, but I believe this is the simplest:
const newString = string.split("data-").pop();
console.log(newString); /// 123
For doing such a thing there are a lot of different ways. A further way could be the following:
let str = 'data-123';
str = str.split('-')[1];
console.log('The remaining string is:\n' + str);
Basically the above code splits the string at the '-' char into two array elements and gets the second one, that is the one with the index 1, ignoring the first array element at the 0 index.
The following is one liner version:
console.log('The remaining string is:\n' + 'data-123'.split('-')[1]);
Another possible approach would be to add a method to the String prototype as follows:
String.prototype.remove = function (s){return this.replace(s,'')}
// After that it will be used like this:
a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk';
a = a.remove('k');
console.log(a);
Notice the above snippet will allow to remove only the first instance of the string you are interested to remove. But you can improve it a bit as follows:
String.prototype.removeAll = function (s){return this.replaceAll(s,'')}
// After that it will be used like this:
a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk';
a = a.removeAll('k');
console.log(a);
The above snippet instead will remove all instances of the string passed to the method.
Of course you don't need to implement the functions into the prototype of the String object: you can implement them as simple functions too if you wish (I will show the remove all function, for the other you will need to use just replace instead of replaceAll, so it is trivial to implement):
function strRemoveAll(s,r)
{
return s.replaceAll(r,'');
}
// you can use it as:
let a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk'
b = strRemoveAll (a,'k');
console.log(b);
Of course much more is possible.
Another way to replace all instances of a string is to use the new (as of August 2020) String.prototype.replaceAll() method.
It accepts either a string or RegEx as its first argument, and replaces all matches found with its second parameter, either a string or a function to generate the string.
As far as support goes, at time of writing, this method has adoption in current versions of all major desktop browsers* (even Opera!), except IE. For mobile, iOS SafariiOS 13.7+, Android Chromev85+, and Android Firefoxv79+ are all supported as well.
* This includes Edge/ Chrome v85+, Firefox v77+, Safari 13.1+, and Opera v71+
It'll take time for users to update to supported browser versions, but now that there's wide browser support, time is the only obstacle.
References:
MDN
Can I Use - Current Browser Support Information
TC39 Proposal Repo for .replaceAll()
You can test your current browser in the snippet below:
//Example coutesy of MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const regex = /dog/gi;
try {
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
console.log('Your browser is supported!');
} catch (e) {
console.log('Your browser is unsupported! :(');
}
.as-console-wrapper: {
max-height: 100% !important;
}
Make sure that if you are replacing strings in a loop that you initiate a new Regex in each iteration. As of 9/21/21, this is still a known issue with Regex essentially missing every other match. This threw me for a loop when I encountered this the first time:
yourArray.forEach((string) => {
string.replace(new RegExp(__your_regex__), '___desired_replacement_value___');
})
If you try and do it like so, don't be surprised if only every other one works
let reg = new RegExp('your regex');
yourArray.forEach((string) => {
string.replace(reg, '___desired_replacement_value___');
})

Replacing Text Inside of Curley Braces JavaScript

I am trying to use JavaScript to dynamically replace content inside of curly braces. Here is an example of my code:
var myString = "This is {name}'s {adjective} {type} in JavaScript! Yes, a {type}!";
var replaceArray = ['name', 'adjective', 'type'];
var replaceWith = ['John', 'simple', 'string'];
for(var i = 0; i <= replaceArray.length - 1; i ++) {
myString.replace(/\{replaceArray[i]\}/gi, replaceWith[i]);
}
alert(myString);
The above code, should, output "This is John's simple string in JavaScript! Yes, a string!".
Here is what happens:
we are given a string with values in braces that need replaced
a loop uses "replaceArray" to find all of the values in curly braces that will need replaced
these values, along with the curly braces, will be replaced with the corresponding values in the "replaceWith" array
However, I am not having any luck, especially since one value may be replaced in multiple locations, and that I am dealing a dynamic value inside of the regular expression.
Can anyone help me fix this, using a similar setup as above?
First, String.replace is not destructive - it doesn't change the string itself, so you'll have to set myString = myString.replace(...). Second, you can create RegExp objects dynamically with new RegExp, so the result of all that would be:
var myString = "This is {name}'s {adjective} {type} in JavaScript! Yes, a {type}!",
replaceArray = ['name', 'adjective', 'type'],
replaceWith = ['John', 'simple', 'string'];
for(var i = 0; i < replaceArray.length; i++) {
myString = myString.replace(new RegExp('{' + replaceArray[i] + '}', 'gi'), replaceWith[i]);
}
The best way I have found to do this, is to use an in-line replace function like others have mentioned, and from whom I borrowed. Special shout out to #yannic-hamann for the regex and clear example. I am not worried about performance, as I am only doing this to construct paths.
I found my solution in MDN's docs.
const interpolateUrl = (string, values) => string.replace(/{(.*?)}/g, (match, offset) => values[offset]);
const path = 'theresalways/{what}/inthe/{fruit}-stand/{who}';
const paths = {
what: 'money',
fruit: 'banana',
who: 'michael',
};
const expected = 'theresalways/money/inthe/banana-stand/michael';
const url = interpolateUrl(path, paths);
console.log(`Is Equal: ${expected === url}`);
console.log(`URL: ${url}`)
Strings are immutable
Strings in JavaScript are immutable. It means that this will never work as you expect:
myString.replace(x, y);
alert(myString);
This is not just a problem with .replace() - nothing can mutate a string in JavaScript. What you can do instead is:
myString = myString.replace(x, y);
alert(myString);
Regex literals don't interpolate values
Regular expression literals in JavaScript don't interpolate values so this will still not work:
myString = myString.replace(/\{replaceArray[i]\}/gi, replaceWith[i]);
You have to do something like this instead:
myString = myString.replace(new RegExp('\{'+replaceArray[i]+'\}', 'gi'), replaceWith[i]);
But this is a little bit messy, so you may create a list of regexes first:
var regexes = replaceArray.map(function (string) {
return new RegExp('\{' + string + '\}', 'gi');
});
for(var i = 0; i < replaceArray.length; i ++) {
myString = myString.replace(regexes[i], replaceWith[i]);
}
As you can see, you can also use i < replaceArray.length instead of i <= replaceArray.length - 1 to simplify your loop condition.
Update 2017
Now you can make it even simpler:
var regexes = replaceArray.map(string => new RegExp(`\{${string}\}`, 'gi'));
for(var i = 0; i < replaceArray.length; i ++) {
myString = myString.replace(regexes[i], replaceWith[i]);
}
Without a loop
Instead of looping and applying .replace() function over and over again, you can do it only once like this:
var mapping = {};
replaceArray.forEach((e,i) => mapping[`{${e}}`] = replaceWith[i]);
myString = myString.replace(/\{\w+\}/ig, n => mapping[n]);
See DEMO.
Templating engines
You are basically creating your own templating engine. If you want to use a ready solution instead, then consider using:
John Resig's Micro-Templating
Mustache
jQuery Templates
Handlebars
doT.js
or something like that.
An example of what you are trying to do using Mustache would be:
var myString = "This is {{name}}'s {{adjective}} {{type}} in JavaScript! Yes, a {{type}}!";
var myData = {name: 'John', adjective: 'simple', type: 'string'};
myString = Mustache.to_html(myString, myData);
alert(myString);
See DEMO.
Here's a function that takes the string and an array of replacements. It's flexible enough to be re-used. The only catch is, you need to use numbers in your string instead of strings. e.g.,
var str = "{0} membership will start on {1} and expire on {2}.";
var arr = ["Jamie's", '11/27/14', '11/27/15'];
function personalizeString(string, replacementArray) {
return string.replace(/{(\d+)}/g, function(match, g1) {
return replacementArray[g1];
});
}
console.log(
personalizeString(str, arr)
)
Demo: https://jsfiddle.net/4cfy7qvn/
I really like rsp's answer. Especially the 'Without a loop' section. Nonetheless, I find the code not that intuitive. I understand that this question comes from the two arrays scenario and that is more than 7 years old, but since this question appears as #1 on google when searching to replace a string with curly braces and the author asked for a similar setup I am tempted to provide another solution.
That being said, a copy and paste solution to play around with:
var myString = "This is {name}'s {adjective} {TYPE} in JavaScript! Yes, a { type }!";
var regex = /{(.*?)}/g;
myString.replace(regex, (m, c) => ({
"name": "John",
"adjective": "simple",
"type": "string"
})[c.trim().toLowerCase()]);
This resource really helped me to build and understand the code above and to learn more about regex with JavaScript in general.

Replacing multiple patterns in a block of data

I need to find the most efficient way of matching multiple regular expressions on a single block of text. To give an example of what I need, consider a block of text:
"Hello World what a beautiful day"
I want to replace Hello with "Bye" and "World" with Universe. I can always do this in a loop ofcourse, using something like String.replace functions availiable in various languages.
However, I could have a huge block of text with multiple string patterns, that I need to match and replace.
I was wondering if I can use Regular Expressions to do this efficiently or do I have to use a Parser like LALR.
I need to do this in JavaScript, so if anyone knows tools that can get it done, it would be appreciated.
Edit
6 years after my original answer (below) I would solve this problem differently
function mreplace (replacements, str) {
let result = str;
for (let [x, y] of replacements)
result = result.replace(x, y);
return result;
}
let input = 'Hello World what a beautiful day';
let output = mreplace ([
[/Hello/, 'Bye'],
[/World/, 'Universe']
], input);
console.log(output);
// "Bye Universe what a beautiful day"
This has as tremendous advantage over the previous answer which required you to write each match twice. It also gives you individual control over each match. For example:
function mreplace (replacements, str) {
let result = str;
for (let [x, y] of replacements)
result = result.replace(x, y);
return result;
}
let input = 'Hello World what a beautiful day';
let output = mreplace ([
//replace static strings
['day', 'night'],
// use regexp and flags where you want them: replace all vowels with nothing
[/[aeiou]/g, ''],
// use captures and callbacks! replace first capital letter with lowercase
[/([A-Z])/, $0 => $0.toLowerCase()]
], input);
console.log(output);
// "hll Wrld wht btfl nght"
Original answer
Andy E's answer can be modified to make adding replacement definitions easier.
var text = "Hello World what a beautiful day";
text.replace(/(Hello|World)/g, function ($0){
var index = {
'Hello': 'Bye',
'World': 'Universe'
};
return index[$0] != undefined ? index[$0] : $0;
});
// "Bye Universe what a beautiful day";
You can pass a function to replace:
var hello = "Hello World what a beautiful day";
hello.replace(/Hello|World/g, function ($0, $1, $2) // $3, $4... $n for captures
{
if ($0 == "Hello")
return "Bye";
else if ($0 == "World")
return "Universe";
});
// Output: "Bye Universe what a beautiful day";
An improved answer:
var index = {
'Hello': 'Bye',
'World': 'Universe'
};
var pattern = '';
for (var i in index) {
if (pattern != '') pattern += '|';
pattern += i;
}
var text = "Hello World what a beautiful day";
text.replace(new RegExp(pattern, 'g'), function($0) {
return index[$0] != undefined ? index[$0] : $0;
});
If the question is how to replace multiple generic patterns with corresponding replacements - either strings or functions, it's quite tricky because of special characters, capturing groups and backreference matching.
You can use https://www.npmjs.com/package/union-replacer for this exact purpose. It is basically a string.replace(regexp, string|function) counterpart, which allows multiple replaces to happen in one pass while preserving full power of string.replace(...).
Disclosure: I am the author and the library was developed because we had to support user-configured replaces.
A common task involving replacing a number of patterns is making a user's or other string "safe" for rendering on Web pages, which means preventing HTML tags from being active. This can be done in JavaScript using HTML entities and the forEach function, allowing a set of exceptions (that is, a set of HTML tags that will be allowed to render).
This is a common task, and here is a fairly brief way to accomplish it:
// Make a string safe for rendering or storing on a Web page
function SafeHTML(str)
{
// Make all HTML tags safe
let s=str.replace(/</gi,'<');
// Allow certain safe tags to be rendered
['br','strong'].forEach(item=>
{
let p=new RegExp('<(/?)'+item+'>','gi');
s=s.replace(p,'<$1'+item+'>');
});
return s;
} // SafeHTML

Categories