replaceAll in javascript and dollar sign - javascript

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.

Related

How to use variables with string.replace()?

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

Escaping backslash in a string containing backslash

I have a string containing I\u2019m (with backslashes not escaped)
var myString = 'I\\u2019m'; // I\u2019m
But then I need a function that 'escape backslashes' that string, so the function I'm looking for would return I'm
backslashString(myString); // I'm
I've tried using eval:
function backslashString(input){
input = input.replace(/'/g, "\\'"); // Replace ' with \' that's going to mess up eval
return eval(`'${input}'`);
}
But is there a proper way of doing it? I'm looking for a function that escape backslashes a string containing I\u2019m to I'm and also handles if there's an extra backslash (A lost \ backslash)
EDIT:
I did not ask what I meant from the start. This not only applies to unicode characters, but applies to all backslash characters including \n
The backslashes aren’t the real problem here - the real problem is the difference between code and data.
\uXXXX is JavaScript syntax to write the Unicode codepoint of a character in a text literal. It gets replaced with the actual character, when the JavaScript parser interprets this code.
Now you have a variable that contains the value I\u2019m already - that is data. This does not get parsed as JavaScript, so it does mean the literal characters I\u2019m, and not I’m. eval can “fix” that, because the missing step of interpreting this as code is simply what eval does.
If you do not want to use eval (and thereby invite all the potential risks that entails, if the input data is not completely under your control), then you can parse those numeric values from the string using regular expressions, and then use String.formCharCode to create the actual Unicode character from the given code point:
var myString = 'I\\u2019m and I\\u2018m';
var myNewString = myString.replace(/\\u([0-9]+)/g, function(m, n) {
return String.fromCharCode(parseInt(n, 16)) }
);
console.log(myNewString)
/\\u([0-9]+)/g - regular expression to match this \uXXXX format (X=digits), g modifier to replace all matches instead of stopping after the first.
parseInt(n, 16) - to convert the hexadecimal value to a decimal first, because String.fromCharCode wants the latter.
decodeURIComponent(JSON.parse('"I\\u2019m"'));
OR for multiple
'I\\\u2019m'.split('\\').join().replace(/,/g,'');
'I\u2019m'.split('\\').join().replace(/,/g,'');
Looks like there's no other way other than eval (JSON.parse doesn't like new lines in strings)
NOTE: The function would return false if it has a trailing backslash
function backslashString(input){
input = input.replace(/`/g, '\\`'); // Escape quotes for input to eval
try{
return eval('`'+input+'`');
}catch(e){ // Will return false if input has errors in backslashing
return false;
}
}

Replace a string fails in some cases

I must check a string and replace something of them.
I have to check if
$mystring='abc...';
has one of this values px,em,%,vh,s
I use this to check the string
function replaceUnit(input){ return input.replace(/(px|em|%|vh|s)/i ,'') }
It works but produces error in some cases.
If I have in my string for example
$mystring="its embeded"
The function will replace the "s" and "em" that's not the way it should be.
The function should check if in mystring is
only a number+px
or only a number+em
or only a number+%
or only a number+vh
or only a number+s
If there is a match, the function should replace the textpart, in all other cases the function should do nothing.
Is it possible to create a kind of this function and how a replace code must be?
Thanks a lot.
UPDATE
based on one of the answears i trie to change it
var input="0s";
function replaceUnit(input)
{
console.log('check: '+input);
var test=input.replace(/(\d)(?:px|em|%|vh|s)$/i ,'');
console.log('->: '+test);
return test
}
the result in the console is
check: 0s
->:
Add a $ (end-of-string anchor) to the end of the regular expression, to ensure that it'll only match if the characters occur at the very end, and capture a number before those characters, so that you can replace with that number alone (thus stripping out the extra characters):
return input.replace(/(\d)(?:px|em|%|vh|s)$/i ,'$1')
https://regex101.com/r/IodB6z/1

javascript - Better Way to Escape Dollar Signs in the String Used By String.prototype.replace

I want to replace a string by another. I found when the replaceValue contains "$", the replace will fail. So I am trying to escape "$" by "$$" first. The code is looks like this:
var str = ..., reg = ...;
function replaceString(replaceValue) {
str.replace(reg, replaceValue.replace(/\$/g, '$$$$'));
}
But I think it is ugly since I need to write 4 dollar signs.
Is there any other charactors that I need to escape? And is there any better way to do this?
There is a way to call replace that allows us not to worry about escaping anything.
var str = ..., reg = ...;
function replaceString(replaceValue) {
return str.replace(reg, function () { return replaceValue });
}
Your method to escape the replacement string is correct.
According to section 15.5.4.11 String.prototype.replace of ECMAScript specification edition 5.1, all special replacement sequences begins with $ ($&, $`, $', $n, $nn) and $$ specify a single $ in the replacement.
Therefore, it is sufficient to escape all $ with double $$ like what you are doing right now if the replacement text is meant to be treated literally.
There is no other concise way to do the replacement as far as I can see.
Unfortunately, nothing you can do about it.
It's just how JavaScript works with regular expressions.
Here's a good article with the list of all replacement patterns you should be aware of:
http://es5.github.io/#x15.5.4.11

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

Categories

Resources