How to remove specific multiple string and then remain another? - javascript

let result = 'Apple%00Juice%02';
const removeOne = result.slice(5, 8); // get %00
const removeTwo = result.slice(13, 16); // get %02
slice get the part of I want to remove not I want to get.
Is any function can let me get the result becomes to 'Apple Juice' ?

You can get the desired result using a regex to match the parts you want to remove from the string and then replace them using the replace() method on strings.
const str = "Apple%00Juice%02";
const regex = /%\d+/g;
const result = str.replace(regex, " ").trim()
console.log(result);
Explanation of regex:
% - match the character % literally
\d+ - match any digit 0 to 9 one or more times
%\d+ - match % character followed by one or more digits

You can achieve this by using .replace() function
Example:
let result = 'Apple%00Juice%02';
result = result.replace('%00', ' ');
result = result.replace('%02', '');
console.log(result);
Read More About .replace() function at MDN Docs
Edit:
Minifying #Yousaf's Answer
let result = "Apple%00Juice%02";
result = result.replace(/%\d+/g, " ").trim()
console.log(result);

It is possible with replace(), but that is not a sustainable solution. The URL encoding "% 00" is the ๏ฟฝ ASCII character. This suggests that the string is already being encoded in the wrong character format for the URL. So you have to look at the character format in which your database or file is read out. for example UTF-8, ISO 8859-1
When encoded in the correct character format. Can you decode it in JavaScript using the decodeURIComponent (str) method.
more on this

Related

find all letters without repeating regex

help me please to find all letters in string without repeating using regex JS.
Examples:
let str = "abczacg";
str = str.match(/ pattern /); // return has to be: abczg
str = "aabbccdd" //return:abcd.
str = "hello world"//return: helo wrd
Is it possible?
Thank you!
Here is one approach. We can first reverse the input string. Then, do a global regex replacement on the following pattern:
(\w)(?=.*\1)
This will strip off any character for which we can find the same character later in the string. But, as we will be running this replacement on the reversed string, this has the actual effect of removing all duplicate letters other than their first occurrence. Finally, we reverse the remaining string again to arrive at the expected output.
var input = "abczacg";
var output = input.split("").reverse().join("").replace(/(\w)(?=.*\1)/g, "");
output = output.split("").reverse().join("");
console.log(output);
An alternative without using a regex using a Set:
[
"abczacg",
"aabbccdd",
"hello world"
].forEach(s => {
console.log([...new Set(s.split(''))].join(''))
})

JavaScript unicode aware string slice

I am trying to slice the string containing Unicode characters. but it returns a replacement character. here is my sample code.
let str = '๐’ฝ๐‘’๐“๐“๐‘œ ๐“Œ๐‘œ๐“‡๐“๐’น';
str = str.slice(0, -1);
console.log(str);
which gives me below result
"๐’ฝ๐‘’๐“๐“๐‘œ ๐“Œ๐‘œ๐“‡๐“๏ฟฝ"
how can I get rid of the replacement character?
Try this, it won't break a 4 byte character into 2:
let str = '๐’ฝ๐‘’๐“๐“๐‘œ ๐“Œ๐‘œ๐“‡๐“๐’น';
str = [...str].slice(0, -1).join('');
console.log(str);
That's because your ๐’น is a surrogate pair, which means that it is represented as four bytes (two code units รก 2 bytes, UTF-16). As .slice works on code units (as all other string methods), you need to slice away the pair:
let str = '๐’ฝ๐‘’๐“๐“๐‘œ ๐“Œ๐‘œ๐“‡๐“๐’น';
str = str.slice(0, -2);
console.log(str);
To work with code points instead of code units you can use the iterator of strings, which will iterate over the code points (that is one character of the string might be a string with two chars):
let str = '๐’ฝ๐‘’๐“๐“๐‘œ ๐“Œ๐‘œ๐“‡๐“๐’น';
for(const char of str)
console.log(char, char.length);
You can use the iterator to build up an array, work on that, and turn the array back into a string as the other answer shows.

How to remove a a substring followed by a dynamic string from a string?

I have the following string
search/year/20212022-2/period/value
And I want to get the results as
search/period/value By removing the year/20212022-2/ from the above string. The year is static but 20212022-2 is dynamic.
How could I do this in jQuery?
You can do it easily with a regular expression:
var str = 'search/year/20212022-2/period/value';
var regex = /(year\/[0-9\-]+\/)/g;
console.log(str.replace(regex, ''));
year/20212022-2 can be in any location inside the string. Just want to remove year followed by a / and string and then again a /
In this case use a regex to find /year/ followed by a string of numbers and hyphens to be replaced, like this:
let input = "search/year/20212022-2/period/value";
let output = input.replace(/\/year\/[\d-]+/g, '');
console.log(output);

Regex in javascript, trying to match but doesn't seem to work with $

EDIT: This question is DIFFERENT. The regex works fine that everyone sent me. The problem is that the $ sign DOESN'T WORK on my string, but it works on others. I can't figure out why and I posted my function below.
I need to find a number at the end of a string, it will be like thisL
My Goal Amount: $25.00/$100.00.
I've tried
var matches = fileDataResult.match(/\d+$/);
but it returns null, I tried it without the $ and it returns the 25, without the .00.
How can I get a variable as a number for the first ones (25.00, with the decimals) and a different variable for the 100.00, with the decimals as well. I need the variables seperate so I can work on them, but I think regex is broken because it won't even work with the $ sign... anyone have suggestion? This is in javascript.
edit:
here is my function, it reads a .txt file and gets the string. I can console.log the string just fine and it work, but it won't work when I use $ in regex!
function fileReaderFunc(file) {
const fileReader = new FileReader();
fileReader.onload = function() {
let fileDataResult = '';
const fileData = fileReader.result;
fileDataResult = fileData.toString();
console.log(fileDataResult);
let str = fileDataResult;
let reg = /\d+(\.\d+)?$/g;
console.log(str.match(reg));
};
fileReader.readAsText(file);
}
let str = "My Goal Amount: $25.00/$100.00.";
str = str.substring(-1,str.length-1); // remove the terminal period
let reg = /\$.+\$.+$/g;
let res = str.match(reg);
let arr = res[0].split('/');
let [num1,num2] = arr;
console.log("1st: ", num1.substring(1, num1.length));
console.log("2nd: ", num2.substring(1, num2.length));
As it turns out this regex is simpler than one might suppose since the text itself includes dollar signs. One can construct a regex that searches for a literal dollar sign followed by other characters and then a second literal dollar sign also followed by other characters from the end of the string marked by a dollar sign symbol minus any slash which signifies the end of a string.
The match is stored in a result array containing one element whose string value is then split on the literal slash mark. The results are then stored in an array arr. Then the values stored in the array are assigned to variables num1 and num2 through array destructuring.
If you prefer a more focused regex, you can also code as follows:
let s = "My Goal Amount: $25.00/$100.00.";
s = s.substring(-1, s.length - 1);
let reg = /\$\d+\.\d+.\$\d+\.\d+$/;
let replaced = s.match(reg)[0].replace(/\$/g, "");
console.log(replaced.split("/"));
If you neglect to trim the string s of the terminal period, then the regex will not match with the string which results in a null. This regex specifies a pattern at the end of the string that starts with a dollar sign,followed by one or more digits then a period and one or more digits. The pattern continues with matching another character (in this case the slash mark) and then a dollar sign followed by one or more digits, next a period and again one or more digits.
First of all \d+ do not match .
You can use this
\d+(\.\d+)?$
Explanation
\d+ - Matches one or more digits.
(\.\d+)? Matches . followed by one or more digit. (? makes it optional )
let str = "abc 125.00";
let reg = /\d+(\.\d+)?$/g;
console.log(str.match(reg))

How can I split the word by numbers but also keep the numbers in Node.js?

I would like to split a word by numbers, but at the same time keep the numbers in node.js.
For example, take this following sentence:
var a = "shuan3jia4";
What I want is:
"shuan3 jia4"
However, if you use a regexp's split() function, the numbers that are used on the function are gone, for example:
s.split(/[0-9]/)
The result is:
[ 'shuan', 'jia', '' ]
So is there any way to keep the numbers that are used on the split?
You can use match to actually split it per your requirement:
var a = "shuan3jia4";
console.log(a.match(/[a-z]+[0-9]/ig));
use parenthesis around the match you wanna keep
see further details at Javascript and regex: split string and keep the separator
var s = "shuan3jia4";
var arr = s.split(/([0-9])/);
console.log(arr);
var s = "shuan3jia4";
var arr = s.split(/(?<=[0-9])/);
console.log(arr);
This will work as per your requirements. This answer was curated from #arhak and C# split string but keep split chars / separators
As #codybartfast said, (?<=PATTERN) is positive look-behind for PATTERN. It should match at any place where the preceding text fits PATTERN so there should be a match (and a split) after each occurrence of any of the characters.
Split, map, join, trim.
const a = 'shuan3jia4';
const splitUp = a.split('').map(function(char) {
if (parseInt(char)) return `${char} `;
return char;
});
const joined = splitUp.join('').trim();
console.log(joined);

Categories

Resources