Javascript Trim as is in C# - javascript

There is JQuery.trim() function but it is trimming the white spaces.
But I want to do it like in C#.
string props = ",width=400,height=400,status=0,location=0,";
props.Trim(',');
// result will be: "width=400,height=400,status=0,location=0"
How can I do this? Actually I would like to use it for general input param not only for ','..

Try an regexp:
var props=",width=400,height=400,status=0,location=0,";
props=props.replace(/^[,]*(.*?)[,]*$/, "$1");
If you, for example, also want to remove semicolons at the beginning or the end, use this:
props=props.replace(/^[,;]*(.*?)[,;]*$/, "$1");
And if you want to remove spaces, too, but only at the end:
props=props.replace(/^[,;]*(.*?)[,; ]*$/, "$1");

I found a link do this with functions and I found another link how to add this function to the String type. And I wrote below code and its test link :
String.prototype.TrimLeft = function (chars) {
//debugger;
var re = chars ? new RegExp("^[" + chars + "]+/", "g")
: new RegExp(/^\s+/);
return this.replace(re, "");
}
String.prototype.TrimRight = function (chars) {
var re = chars ? new RegExp("[" + chars + "]+$/", "g")
: new RegExp(/\s+$/);
return this.replace(re, "");
}
String.prototype.Trim = function (chars) {
return this.TrimLeft(chars).TrimRight(chars);
}
^[" + chars + "]+ is finding the characters at the begining of string.
And it is replacing on this line: this.replace(re, "");
With this : [" + chars + "]+$, it is searching characters at the end of string g(globally) and replacing with the same method.
var c=",width=400,height=400,status=0,";
c.Trim(",");
// result: width=400,height=400,status=0

Related

how to get special character from string in nodejs and replace

how to find specific special character from string and replace it to unicode \u0026 + = \u002B
replace only these special character : [$, &, +, #]
example : "HELLO JAMES (WITH ME YOUR) \n+++ SEE & FIELD 4-B +++
MY code
var char = '+';
var saa =char.charCodeAt(0);
console.log(saa)
var codeHex = saa.toString(16).toUpperCase();
while (codeHex.length < 4) {
codeHex = "0" + codeHex;
}
var afteruni = name.replaceAll('\+','\\u'+codeHex)
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
i want like this :
"HELLO JAMES (WITH ME YOUR) \n\u002B\u002B\u002B SEE \u0026 FIELD 4-B
\u002B\u002B\u002B"
ERROR : Invalid regular expression: /+/: Nothing to repeat\
you don't need to redefined replaceAll - why do that? replaceAll will already give you a correct response :
just replace line: var afteruni = name.replaceAll('\+','\\u'+codeHex)
with var afteruni = name.replaceAll(/\+/g,'\\u'+codeHex)
iv'e run that in my PC and it is working.

Regex not working for multiple characters

I want to search and replace special characters of markdown (viz \`*_{}[]()#+.!|-) from the given string.
I am able to make it work in C# easily since there is verbatim # but Javascript not getting what's the issue. It seems something to do with /g , I read in another post which asked to use replaceAll but I could not find that method for string
C# version
string test = #"B
*H*
C
**AB**";
Console.WriteLine ("Input " + test);
var pattern = #"[\\`*_{}\[\]()#+-.!]";
var _1 = Regex.Replace (test, "\r?\n", "<br/>");
var out_ = Regex.Replace (_1, pattern, m => #"\" + m.Value);
Console.WriteLine ("Output " + out_);
Typescript Version
const regexM = new RegExp(/[\\\`\*\_\{\}\[\]\(\)#\+-\.!\|]/g, 'm');
var input = `B
*H*
C
**AB**`;
var inputString = input.replace(regexM, function (y: any) { return "\\" + y; });
if (/\r|\n/.exec(inputString))
{
inputString = inputString .replace(/\r?\n/g, "<br/>");
}
inputString = inputString.replace(regexM, function (x: any)
{
return "\\" + x;
});
Expected: B <br/>\*H\*<br/>C<br/>\*\*AB\*\*
I am getting B <br/>\*H*<br/>C<br/>**AB**
You may use
const regexM = /[\\`*_{}[\]()#+.!|-]/g;
var input = `B
*H*
C
**AB**`;
var inputString = input.replace(regexM, "\\$&");
inputString = inputString.replace(/\r?\n/g, "<br/>");
console.log(inputString);
// => B <br/>\*H\*<br/>C<br/>\*\*AB\*\*
NOTE:
The - in the regexM regex forms a range, you need to either escape it or - as in the code above - put it at the end of the character class
Rather than using callback methods, in order to reference the whole match, you may use the $& placeholder in a string replacement pattern
When you define the regex using a regex literal, there is only one backslash needed to form a regex escape, so const regexM = /[\\`*_{}[\]()#+.!|-]/g is equal to const regexM = new RegExp("[\\\\`*_{}[\\]()#+.!|-]", "g")
There is no need to check if there is a line break char or not with if (/\r|\n/.exec(inputString)), just run .replace.

JavaScript replace all but last whilst preserving original line breaks

I have some code which outputs as follows:
function replaceAllButLast(str, splitRegex, pOld, pNew) {
var parts = str.split(splitRegex)
if (parts.length === 1) return str
return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
}
var str = "fred\r\nfred\r\nfred\r\n"
var desiredResult = replaceAllButLast(str, /(?:\r?\n|\r)/, '\n', '\n+')
console.log(desiredResult)
The result is nearly as desired. However, the code assumes that the regex split operation is splitting on \n and thus is replacing it with \n
However, it may actually be splitting on \r\n (windows - as in the example) or \r (old macs)
Does anyone have some code that would give the same output as the code here BUT will preserve the original line break characters whilst still adding the + after a newline (except on the last line).
I am using pure vanilla JavaScript.
PS I must use the regex /(?:\r?\n|\r)/
PPS There is no need to use .split().
This will keep the last newline as it is but others added a +, see replace
var str = "fred\r\nfred\r\nfred\r\n";
var splitRegexp = new RegExp(/(?:\r?\n|\r)/, 'g')
var newstr = str.replace(splitRegexp, function(match, offset, string) {
var follow = string.slice(offset);
var isLast = follow.match(splitRegexp).length == 1;
if (!isLast) {
return match + '+';
} else {
return match;
}
})
console.log(newstr)
I've replaced your regexp with visible chars so you can see what's going on:
var input = "fredEOLfredENDLfredFINfred";
input = input.replace(/(EOL|ENDL|FIN)/g, "$1+");
console.log(input);

String replace module definition

Below I'm trying to replace the moduleName string with another string replacementModule.
var replacementModule = 'lodash.string' // cheeky
var moduleName = 'underscore.string'
var pattern = new RegExp('^' + moduleName + '(.+)?')
var match = definition.match(pattern)
var outcome = replacementModule + match[1]
However right now a totally different module is matched as well.
underscore.string.f/utils // desired no change
underscore.string.f // desired no change
underscore.string // => lodash.string
underscore.string/utils // => lodash.string/utils
How can I match to the /, and how the outcome that I expect?
You need to do at least 3 things:
Escape the string variable passed to the RegExp
Check if match is null before using it
The regex should contain ($|/.*) as capturing group 1 to match either an end of string or / followed by 0 or more characters.
RegExp.escape = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
function runRepl(definition, replacementModule, moduleName) {
var pattern = RegExp('^' + RegExp.escape(moduleName) + '($|/.*)');
// ^------------^ ^------^
var match = definition.match(pattern);
if (match !== null) { // Check if we have a match
var outcome = replacementModule + match[1];
document.write(outcome + "<br/>");
}
else {
document.write("N/A<br/>");
}
}
runRepl("underscore.string.f/utils", "lodash.string", "underscore.string");
runRepl("underscore.string.f", "lodash.string", "underscore.string");
runRepl("underscore.string", "lodash.string", "underscore.string");
runRepl("underscore.string/utils", "lodash.string", "underscore.string");
Escaping is necessary to match a literal . inside moduleName and ($|/)(.+)? presumes there can be something after an end of string. Also, (.+)? (1 or more characters) is actually the same as .* which is shorter and easier to read.

Regular Expression: replace string in javascript

I want a regular expression to match a string like this "(192)"
the string starts with "(" and ends with ")" and numbers from 0 to 9 go between the parentheses.
I've tried this function before but it does not work:
function remove_garbage_numbers(str) {
var find = '^\([0-9]\)$';
var re = new RegExp(find, 'g');
return str.replace(re, '');
}
You don't need to pass this to RegExp constructor. And you don't need to have a g modifier when anchors are used. And aso when anchors are used, it's safe to use m multiline modifier.
var find = /^\([0-9]+\)$/m;
ie,
function remove_garbage_numbers(str) {
var re = /^\([0-9]+\)$/m;
return str.replace(re, '');
}
OR
var re = new RegExp("^\\([0-9]+\\)$", 'm');
ie,
function remove_garbage_numbers(str) {
var re = new RegExp("^\\([0-9]+\\)$", 'm');
return str.replace(re, '');
}
Update
> "Main (191)|Health & Beauty (6)|Vision Care (8)".replace(/\(\d+\)/g, "")
'Main |Health & Beauty |Vision Care '

Categories