Is there any function that can do .trim for specified characters or string?
Something like:
var x = '###hello world##';
console.log(x.trim('#')); // prints 'hello world'
var y = 'hellohellohelloworld';
console.log(y.trim('hello')); // prints ' world'
var z = '##hello#world##';
console log(z.trim('#')); // prints 'hello#world'
Even tho I can do without this, it would be way less efficient and not as clean
You can use a pattern with an alternation | to match either what you want to remove at the start or at the end of the string by repeating it 1 or more time in a non capture group.
The repetition looks like this (?:#)+ for a single # char, or like this (?:hello)+ for the word hello
If you want to make a function for it and want to pass any string, you have to escape the regex meta characters with a \
var x = '###hello world##';
var y = 'hellohellohelloworld';
var z = '##hello#world##';
var a = '*+hello*+'
const customTrim = (strSource, strToRemove) => {
let escaped = strToRemove.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
return strSource.replace(new RegExp(`^(?:${escaped})+|(?:${escaped})+$`, 'g'), "")
};
console.log(customTrim(x, "\\s"));
console.log(customTrim(y, "hello"));
console.log(customTrim(z, "#"));
console.log(customTrim(a, "*+"));
export function trim(str: string, char: string): string {
const leading = new RegExp(`^[${char}]+`);
const trailing = new RegExp(`[${char}]+$`);
return str.replace(leading, "").replace(trailing, "");
}
Related
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.
I have a string in which i want to remove some part.
1) below is the string( Encrypted message)
##_/profiles/c3ed4acd-b3be-487e-81b4-a27643745d^^____User1__###^^^ says hello to ##_/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e^^____User2__###^^^
I want to get below 2 things from this
a) A string
#User1 says to #User2
2) A json object like
{
"c3ed4acd-b3be-487e-81b4-a27643745d":"User1",
"d3ac3c5a-8a9f-4640-8563-127674d93e":"User2"
}
First I tried to get string and used below approach using regex
I have tried it by doing like this
var str = "##___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__###^^^ says to ##___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__###^^^"
var rx = /(^##___|,###^^^)/; // start with ##___ and end with ###^^^
var expectedString = str.replace(/(^##___|,###^^^)/g, "");
console.log(expectedString);
But this is just replace first occurance of
There are some fundamental problems in your code
you have to escape the ^ character as \^
you don't even use your rx variable
pipe character | means or, not start with and end with
try this:
// a)
var str = "##___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__###^^^ says to ##___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__###^^^"
var rx = /##___([^_]+)__\^\^____([^_]+)__###\^\^\^/g;
var expectedString = str.replace(rx, "#$2");
console.log(expectedString);
// b)
var list = {};
while ((m = rx.exec(str)) !== null) {
if (m.index === rx.lastIndex) {
rx.lastIndex++;
}
list[m[1]] = m[2];
}
console.log(list);
trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.
In my application, I have an alphanumeric string being passed into my function. This string is typically 17 characters, but not always. I'm trying to write a regex that matches all but the last 4 characters in the string, and replaces them with X (to mask it).
For example
Input: HGHG8686HGHG8686H
Output: XXXXXXXXXXXXX686H
The Regex I wrote to perform the replace on the string is as follows
[a-zA-Z0-9].{12}
Code:
const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');
The issue I'm having is that it's replacing all but the last 4 characters in the string with just that single X. It doesn't know to do that for every matched character. Any ideas?
you can use a function inside replace to do this, something like this will do:
var str = "HGHG8686HGHG8686H"
var regexp = /[a-zA-Z0-9]+(?=....)/g;
var modifiedStr = str.replace(regexp, function ($2) {
return ('X'.repeat($2.length +1));
});
console.log(modifiedStr);
The simple version: (Easier to read)
const maskedString = string.replace(/(.{4})$|(^(..)|(.))/g, 'X\1'); // or X$1
Now using: [a-zA-Z0-9]
const maskedString = string.replace(/([a-zA-Z0-9]{4})$|(^([a-zA-Z0-9]{2})|([a-zA-Z0-9]{1}))/g, 'X\1'); // or X$1
Note: The reason i match on the START PLUS TWO characters is to offset the first match. (The final 4 characters that are appended at the end.)
Look ahead (?=) to make sure there are at least four following characters.
const regex = /.(?=....)/g;
// ^ MATCH ANYTHING
// ^^^^^^^^ THAT IS FOLLOWED BY FOUR CHARS
function fix(str) { return str.replace(regex, 'X'); }
const test = "HGHG8686HGHG8686H";
// CODE BELOW IS MERELY FOR DEMO PURPOSES
const input = document.getElementById("input");
const output = document.getElementById("output");
function populate() { output.textContent = fix(input.value); }
input.addEventListener("input", populate);
input.value = test;
populate();
<p><label>Input: </label><input id="input"></p>
<p>Output: <span id="output"></span></p>
A non-regexp solution:
const test = "HGHG8686HGHG8686H";
function fix(str) {
return 'X'.repeat(str.length - 4) + str.slice(-4);
}
console.log(fix(test));
You will not find String#repeat in IE.
You can achieve using following method:
var str = "HGHG8686HGHG8686H"
var replaced=''
var match = str.match(/.+/)
for(i=0;i<match[0].length-4;i++){
str = match[0][i]
replaced += "X"
}
replaced += match[0].substr(match[0].length-4)
console.log(replaced);
I am trying to get the regular expression that accepts only characters with specific pattern like two characters separated by comma, but I am not able to get it.
Here i included the acceptable sting
string = ab,ca,ls,gz,tv......
I tried:
/^([a-zA-Z]{2},)|([a-zA-Z]{2})*$/
but it is not working as expected.
Try using /^[a-z]{2}(?:,[a-z]{2})*$/i instead (the | inside your pattern was problematic):
var string = 'ab,ca,ls,gz,tv'
var regex = /^[a-z]{2}(?:,[a-z]{2})*$/i
console.log(regex.test(string)) //=> true
If I'm understanding you correctly, then you're trying to get (capture) the 2 characters, with the condition that they're within the bounds of a comma or at the start or end of a line:
(?:^|,)([a-zA-Z]{2})(?=,|$)
Live preview
var string = "ab,ca,ls,gz,tv";
const regex = /(?:^|,)([a-zA-Z]{2})(?=,|$)/g;
match = regex.exec(string);
while (match != null) {
console.log(match[1]);
match = regex.exec(string);
}
The above outputs:
ab
ca
ls
gz
tv
Try this.
/^[a-z]{2}(,[a-z]{2})*$/i
var string1 = "ab,ca,ls,gz,tv"
var string2 = "ab,c,ls"
var string3 = "ab,ca"
var regex = /^[a-z]{2}(,[a-z]{2})*$/i
document.getElementById("test").innerHTML =
regex.test(string1) + "<br>" + // true
regex.test(string2) + "<br>" + // false
regex.test(string3) // true
<p id="test"></p>