How to use variables with string.replace()? - javascript

I need to replace a lot of characters in a string. So I built two strings. One is called strSearch which contains all characters I want to replace. The other is strReplace which contains all the characters which would replace the respective characters of strSearch. It looks like this:
var strSearch="\n\t,.", strReplace="//T#!";
I would like to run a for loop which each character of strSearch and replace it with the character of the same index in strReplace. The issue is that string.replace() does not encapsulate the first argument in quotes, thereby making it impossible to pass variables in it.
I could manually create a string.replace() statement using eval() for each iteration of the loop, but I despise the idea of using eval().
Is there any other way I can pass variables for string.replace()?

You can use String.prototype.replaceAll and replace all the characters in the from array with respective characters in the to array.
const replaceChars = (str, from, to) =>
Array.from(from).reduce((s, ch, i) => s.replaceAll(ch, to[i]), str);
console.log(replaceChars("mango", "ma", "bi"));
console.log(replaceChars("banana", "ab", "on"));

Related

string replace using a regex

I have a string after Json.stringify in javascript using node. I wanted to replace the text in the string which starts with 'ab' then followed by some numbers(atleast one digit), with 'ab^^^^^^' where the number of '^' s should be equal to the number of digits after ab. The text starting with ab can occur atleast once, In this example it occurs twice. I need help in regex and replacing the string
string - in this, text starting with ab occurs twice.
var str = JSON.stringify({"abc":{"idcardno":"ertyuiop","form":{"somestring":"This string:\n- can have multiple \nab12345ab5677\n","flag":"true","flag2":"false"},"anothertext":"samplestring","numbetstr":"7"}});
after the regex replace it should be like this
{"abc":{"idcardno":"ertyuiop","form":{"somestring":"This string:\n- can have multiple \na^^^^^ab^^^^\n","flag":"true","flag2":"false"},"anothertext":"samplestring","numbetstr":"7"}}
Edit
As per the post below the below will be the contents of obj.abc.form.string, coming in multiple lines. How do I do the regex(above mentioned) replace of this object?
This string:
- can have multiple
ab12345ab56778
Don't process stringifed JSON with regexp. Process the JavaScript object itself, then stringify. In your case, assuming obj is the input:
obj.abc.form.somestring = transform(obj.abc.form.somestring);
str = JSON.stringify(obj);
where transform is a regexp/replace making the transformation you want.
#torazaburo is right, it's a bad practice to manipulate JSON directly. Once you get ahold of the string in obj.abc.form.somestring, though, you can use replace, passing a function:
str.replace(/ab\d+/g, function(match) {return match.replace(/\d/g,'^')})

How to read all string inside parentheses using regex

I wanted to get all strings inside a parentheses pair. for example, after applying regex on
"fun('xyz'); fun('abcd'); fun('abcd.ef') { temp('no'); "
output should be
['xyz','abcd', 'abcd.ef'].
I tried many option but was not able to get desired result.
one option is
/fun\((.*?)\)/gi.exec("fun('xyz'); fun('abcd'); fun('abcd.ef')").
Store the regex in a variable, and run it in a loop...
var re = /fun\((.*?)\)/gi,
string = "fun('xyz'); fun('abcd'); fun('abcd.ef')",
matches = [],
match;
while(match = re.exec(string))
matches.push(match[1]);
Note that this only works for global regex. If you omit the g, you'll have an infinite loop.
Also note that it'll give an undesired result if there a ) between the quotation marks.
You can use this code will almost do the job:
"fun('xyz'); fun('abcd'); fun('abcd.ef')".match(/'.*?'/gi);
You'll get ["'xyz'", "'abcd'", "'abcd.ef'"] which contains extra ' around the string.
The easiest way to find what you need is to use this RegExp: /[\w.]+(?=')/g
var string = "fun('xyz'); fun('abcd'); fun('abcd.ef')";
string.match(/[\w.]+(?=')/g); // ['xyz','abcd', 'abcd.ef']
It will work with alphanumeric characters and point, you will need to change [\w.]+ to add more symbols.

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 :)

replaceAll in javascript and dollar sign

I have a string with 3 dollar signs e.g. $$$Test123. I would like to display this string in a div.
The problem is that when I use replace I get $$Test123 - 2 dollar signs instead of 3.
example:
var sHtml="<_content_>";
var s="$$$Test";
sHtml= sHtml.replace("<_content_>", s);
Now the result of sHtml is $$Test;
Any idea how can it be solved?
javascript does not have a default replace all function. You can write your own like this
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'),with_this);
}
$ has a special meaning when included in a string for the second argument of a call to replace(). Normally, you would use it to refer to matched expressions within the original string. For example:
"foo foooo".replace(/fo+/g, "$&bar");
//-> "foobar foooobar"
In the example above, $& refers back to the entire match, which is foo in the first word and foooo in the second.
Your problem stems from the special meaning of $. In order to use a literal $ in the match, you must chain two together so that the first escapes the second. To have 3 literal $ symbols, you must chain 6 together, like so:
var sHtml="<_content_>";
var s="$$$$$$Test";
sHtml= sHtml.replace("<_content_>", s);
//-> "$$$Test"
Quotes are your friend
var sHtml="<_content_>"
var s="$$$Test";
sHtml= sHtml.replace("<_content_>", s);
Try this replaceAll function:
http://www.dumpsite.com/replaceAll.php
It performs a replace all using the javascript replace function via a regular expression for speed, and at the same time eliminates the side effects that occur when regular expression special characters are inadvertently present in either the search or replace string.
Using this function you do not have to worry about escaping special characters. All special characters are pre escaped before the replaceAll is preformed.
This function will produce the output you are expecting.
Try it out and provide your feeback.

regex for nested values

I'm trying to get the numbers/stings out of a string that looks like this
"[123][456][abc]"
Also I don't want to include "[" or "]" and I want to keep the values separate.
Try this on for size.
/\[(\d+|[a-zA-Z]+)\]/
Edit:
If you can support lookahead and lookbehind
/(?<=\[)(\d+|[a-zA-Z]+)(?=\])/
Another edit:
try this in javascript
var text = "[12][34][56][bxe]";
var array = text.match(/(\d+|[a-zA-Z]+)/g);
This would be a lot easier if we knew the language. For example, in Javascript you can do:
"[123][456][abc]".split(/[\[\]]/);
and similarly in Python:
>>> import re
>>> re.split(r'[\[\]]', "[123][456][abc]")
['', '123', '', '456', '', 'abc', '']
I'm sure there are ways to do this in other languages, too.
See http://www.regular-expressions.info/javascript.html, particularly the "How to Use The JavaScript RegExp Object" section:
If you want to retrieve the part of
the string that was matched, call the
exec() function of the RegExp object
that you created, e.g.: mymatch =
myregexp.exec("subject"). This
function returns an array. The zeroth
item in the array will hold the text
that was matched by the regular
expression. The following items
contain the text matched by the
capturing parentheses in the regexp,
if any. mymatch.length indicates the
length of the match[] array, which is
one more than the number of capturing
groups in your regular expression.
mymatch.index indicates the character
position in the subject string at
which the regular expression matched.
mymatch.input keeps a copy of the
subject string.
That explains how to access individual parenthesized groups. You can use that in conjunction with a pattern like /\[(\w+)\]/g

Categories

Resources