Javascript String replace isn't replacing my parameter [duplicate] - javascript

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 2 years ago.
I have the following string:
"Write the conjugate of each radical expression.\n\n**(a)** `$2\\sqrt{3} - 4$`\n\n**(b)** `$\\sqrt{3} +\\sqrt{2}$`\n\n**(c)** `$-2\\sqrt{3} - \\sqrt{2}$`\n\n**(d)** `$3\\sqrt{3} + \\sqrt{2} $`\n\n**(e)** `$\\sqrt{2} - \\sqrt{5}$`\n\n**(f)** `$-\\sqrt{5} + 2\\sqrt{2}$`"
And I have the following function to go through a string and replace substrings:
var changeString = function(markdownStr) {
return markdownStr.replace(/`/g, "").replace("$ ", "$").replace(" $", "$");
};
The result I get is that it replaces some of the conditions (the `), but it didn't work for the last replace condition (" $").
Here is the output:
Write the conjugate of each radical expression. **(a)**$2\sqrt{3} - 4$ **(b)** $\sqrt{3} +\sqrt{2}$ **(c)** $-2\sqrt{3} - \sqrt{2}$ **(d)** $3\sqrt{3} + \sqrt{2} $ **(e)** $\sqrt{2} - \sqrt{5}$ **(f)** $-\sqrt{5} + 2\sqrt{2}$
You can see for the (d) option, it still outputs as $3\sqrt{3} + \sqrt{2} $ but I expected it to be $3\sqrt{3} + \sqrt{2}$.
What is going on and why isn't it replacing it?
Here is a codepen example:
https://codepen.io/jae_kingsley/pen/MWyWZbN

From W3Schools
If you are replacing a value (and not a regular expression), only the
first instance of the value will be replaced
So you should probably use regular expressions for all replaces, not just the first one. Don't forget you'll have to escape the $:
.replace(/\s\$/g, '$')

Changing you code to following will work as it accounts for any $ with space before or after or none. So it will match $, $ , $, $ etc.
var changeString = function(markdownStr) {
return markdownStr.replace(/`/g, "").replace(/\s*\$\s*/g, '$');
};

Related

Javascript : replace HTML-Charakters with ASC2 Charakters [duplicate]

This question already has answers here:
Unescape HTML entities in JavaScript?
(33 answers)
Closed 19 days ago.
is there a special function for this replacement in Javascript ?
(replaceAll)
PARAMS+= "&Ueberschrift=" + ueberschrift.replaceAll(">",">").replaceAll("<","<");
PARAMS+= "&TextBaustein=" + textBaustein.replaceAll(">",">").replaceAll("<","<");
PARAMS+= "&Beurteilung=" + beurteilung.replaceAll(">",">").replaceAll("<","<");
edit: there is a replaceAll() method in JS, my bad !
anyhow, you can use the replace() method and use a regular expression to replace all occurrences of a string, taken from your provided example you could do something like this:
PARAMS += "&Ueberschrift=" + ueberschrift.replace(/\>/g, ">").replace(/\</g, "<"); PARAMS += "&TextBaustein=" + textBaustein.replace(/\>/g, ">").replace(/\</g, "<"); PARAMS += "&Beurteilung=" + beurteilung.replace(/\>/g, ">").replace(/\</g, "<");
To elaborate:
'g' flag indicates that the replacement should occur for all matches (not just the first one)
> and < characters are escaped to match the actual > and < characters.
'&gt' and '&lt' (HTML escape codes for '>' and '<')

How can i get all get substring from a complex string using regex or any other solution? [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 3 years ago.
Input should be like this:
class1{name=‘adam.smith’}.class2{name=‘john’}.subjectMath
Output something like:
["class1{name='adam.smith'}", "class2{name='john'}", "subjectMath"]
Any solution?
Try using split:
var input = "class1{name=‘adam.smith’}.class2{name=‘john’}.subjectMath";
var parts = input.split(/\.(?![^{]*’)/);
console.log(parts);
The regex used for the split requires some explanation:
\. match a literal dot
(?![^{]*’) but assert that we DON'T encounter a text curly quote
looking forward so long as we don't hit a { first
The negative lookahead fails the dot in adam.smith, because we can find a curly quote without encountering a { opening bracket, which would imply that the dot is not a connecting dot.
Giving a sting like this:
string = "class1{name=‘adam.smith’}.class2{name=‘john’}.subjectMath";
You could try with this:
string.split(/(?<=})./)
which will return:
[ "class1{name=‘adam.smith’}" , "class2{name=‘john’}" , "subjectMath" ]
Swift 5.1
This is a solution for Swift assuming that the input structure remains the same, with the bracket preceding the dot :
var input = "class1{name=‘adam.smith’}.class2{name=‘john’}.subjectMath"
func splittingClasses(_ input: String) -> [String] {
var total: [String] = []
var parts = input.components(separatedBy: "}.")
let endpart = "}"
for i in 0 ..< parts.count {
if i == parts.count - 1 {
total.append(parts[i])
} else {
total.append(parts[i] + endpart)
}
}
print(total)
return total
}
splittingClasses(input)
// returns ["class1{name=‘adam.smith’}", "class2{name=‘john’}", "subjectMath"]
You could match everything that is not an . of course this gives some issues with the . within ‘...’ context. For this reason we should also match those.
const input = "class1{name=‘adam.smith’}.class2{name=‘john’}.subjectMath";
const output = input.match(/(?:‘[^’]*’|[^.])+/g);
console.log(output);
‘[^’]*’
Will match any ‘ and keeps matching until it finds the closing ’ character, matching anything in-between.
[^.]
Will match anything that is not a . character.

meaning of javascript sign $? [duplicate]

This question already has answers here:
Usage of the backtick character (`) in JavaScript
(11 answers)
Closed 4 years ago.
scuse me , what does that mean inside of a javascript program text
console.log(`${ingredientAmount} ${unit} ${name}`); ?
This is the textprogram containing the line mentioned before:
const hummus = function(factor) {
const ingredient = function(amount, unit, name) {
let ingredientAmount = amount * factor;
if (ingredientAmount > 1) {
unit += "s";
}
console.log(`${ingredientAmount} ${unit} ${name}`);
};
ingredient(1, "can", "chickpeas");
ingredient(0.25, "cup", "tahini");
ingredient(0.25, "cup", "lemon juice");
ingredient(1, "clove", "garlic");
ingredient(2, "tablespoon", "olive oil");
ingredient(0.5, "teaspoon", "cumin");
};
That's a template literal / template string, the ${ and } are the tokens to define placeholders that would be replaced by the value of the expression inside them.
So this:
console.log(`${ ingredientAmount } ${ unit } ${ name }`);
With a normal string would be:
console.log(ingredientAmount + ' ' + unit + ' ' + name);
${} in Javascript's ES6 world signals Javascript that while parsing that literal, it's going to find an expression to evaluate inside the curly brackets, which means that when creating a String from the template literal, these parts are going to be replaced by whatever value the expression inside evaluates to at the time of parsing. Backticks enclose the template literal:
`** literal here**`
The expression can not only be variables like shown by you, it could as well be something other like
`Today's date is ${new Date()}. Have a beautiful day!`
or
`The random number of the moment is ${Math.random()}.`

Replace nth occurrence of a special character not working RegEx with Google Script [duplicate]

This question already has an answer here:
Javascript regex match fails on actual page, but regex tests work just fine
(1 answer)
Closed 4 years ago.
I am trying to replace the nth occurrence of a character with the following function
It works for strings of letters but I want to replace the 2nd [ in [WORLD!] HELLO, [WORLD!]
I am trying the pattern /.\\[/ which works in RerEx tester but not in my function. I get no error just no replacement
Thanks
function ReplaceNth_n() {
Logger.log(ReplaceNth("[WORLD!] HELLO, [WORLD!]", "/.\\[/", "M", 2))
}
function ReplaceNth(strSearch,search_for, replace_with, Ocur) {
var nth = 0;
strSearch = strSearch.replace(new RegExp(search_for, 'g'), function (match, i, original) {
nth++;
return (nth === Ocur) ? replace_with : match;
});
return strSearch
}
When you create a regular expression with RegExp, you should not include the opening and closing / in the string, and I also don't understand why you added a . there.
Wrong: new RegExp("/test/");
Correct: new RegExp("test");
So the string passed as parameter for search_for should be \\[.
The nth occurrence.
^([^<char>]*(?:<char>[^<char>]*){<N-1>})<char>
Replace with $1<repl_char>
Where the regex string is constructed
regexStr = '^([^' + char + ']*(?:' + char + '[^' + char + ']*){' + (N-1) + '})' + char;
Where char is to be found and N > 0

Escape string for use in Javascript regex [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a RegExp.escape function in Javascript?
I am trying to build a javascript regex based on user input:
function FindString(input) {
var reg = new RegExp('' + input + '');
// [snip] perform search
}
But the regex will not work correctly when the user input contains a ? or * because they are interpreted as regex specials. In fact, if the user puts an unbalanced ( or [ in their string, the regex isn't even valid.
What is the javascript function to correctly escape all special characters for use in regex?
Short 'n Sweet (Updated 2021)
To escape the RegExp itself:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
To escape a replacement string:
function escapeReplacement(string) {
return string.replace(/\$/g, '$$$$');
}
Example
All escaped RegExp characters:
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
Find & replace a string:
var haystack = "I love $x!";
var needle = "$x";
var safeNeedle = escapeRegExp(needle); // "\\$x"
var replacement = "$100 bills"
var safeReplacement = escapeReplacement(replacement); // "$$100 bills"
haystack.replace(
new RegExp(safeNeedle, 'g'),
escapeReplacement(safeReplacement),
);
// "I love $100 bills!"
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!## ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
Test Case: A typical url
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
The Long Answer
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!##$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());

Categories