Replace 2 characters inside a string in JavaScript - javascript

I have this string and I want to fill all the blank values with 0 between to , :
var initialString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,
I want this output :
var finalString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,0,0,1,0
I try to use replace
var newString = initialString.replace(/,,/g, ",0,").replace(/,$/, ",0");
But the finalString looks like this:
var initialString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,0,,1,0
Some coma are not replaced.
Can someone show me how to do it?

You can match a comma which is followed by either a comma or end of line (using a forward lookahead) and replace it with a comma and a 0:
const initialString = '3,816,AAA3,aa,cc,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,';
let result = initialString.replace(/,(?=,|$)/g, ',0');
console.log(result)

using split and join
var str = "3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,";
const result = str
.split(",")
.map((s) => (s === "" ? "0" : s))
.join(",");
console.log(result);

Related

Convert currency to decimal number JavaScript

How can I convert currency string like this $123,456,78.3 to number like this 12345678.3
I tried to do using this pattern
let str = "$123,456,78.3";
let newStr = str.replace(/\D/g, '');
but it replaces . too.
var str = "$123,456,78.3";
var newStr = Number(str.replace(/[^0-9.-]+/g,""));
Use a lowercase d, and put it into a negated character group along with the ..
let str = "$123,456,78.3";
let newStr = str.replace(/[^\d.]/g, '');
console.log(newStr)
You can use a negative character group:
"$123,456,78.3".replace(/[^\d.]/g, "")

How to get the delimiters that split my string in Javascript?

Let's say I have a string like the following:
var str = "hello=world&universe";
And my regex replace statement goes like this:
str.replace(/([&=])/g, ' ');
How do I get the delimiters that split my string from the above regex replace statement?
I would like the result to be something like this:
var strings = ['hello', 'world', 'universe'];
var delimiters = ['=', '&'];
You could split with a group and then separate the parts.
var str = "hello=world&universe",
[words, delimiters] = str
.split(/([&=])/)
.reduce((r, s, i) => {
r[i % 2].push(s);
return r;
}, [[], []]);
console.log(words);
console.log(delimiters);
Here's one way using String.matchAll
const str = "hello=world&universe";
const re = /([&=])/g;
const matches = [];
let pos = 0;
const delimiters = [...str.matchAll(re)].map(m => {
const [match, capture] = m;
matches.push(str.substring(pos, m.index));
pos = m.index + match.length;
return match;
});
matches.push(str.substring(pos));
console.log('matches:', matches.join(', '));
console.log('delimiters:', delimiters.join(', '));
But just FYI. The string you posted looks like a URL search string. You probably want to use URLSearchParams to parse it as there are edge cases if you try to split on both '&' and '=' at the same time. See How can I get query string values in JavaScript?

RegEx replacing numbers greater than variable in Javascript

I have the string:
"selection1 selection2 selection3 selection4"
I am looking to remove all words that end in a number greater than a variable. For instance:
let str = "selection1 selection2 selection3 selection4";
let x = 2;
let regExp = RegExp(...);
let filtered = str.replace(regExp , ""); // should equal "selection1 selection2"
I came up with the following expression which selects all words that end in numbers greater than 29:
/(selection[3-9][0-9]|[1-9]\d{3}\d*)/gi
The result from this regEx on the string "selection1 selection 40" is [selection40]
I feel that I'm part of the way there.
Given that I'm dealing with single and double digit numbers and am looking to incorporate a variable, what regEx could help me alter this string?
You can use .replace with a callback:
let str = "selection5 selection1 selection2 selection3 selection4";
let x = 2;
let regex = /\s*\b\w+?(\d+)\b/g;
let m;
let repl = str.replace(regex, function($0, $1) {
return ($1 > x ? "" : $0);
}).trim();
console.log( repl );
Regex /\b\w+?(\d+)\b/g matches all the words ending with 1+ digits and captures digits in capture group #1 which we use inside the callback function to compare against variable x.
You can split by whitespace, then capture the group using Regex which gets the only the numeric part and filter it accordingly.
const str = "selection1 selection2 selection3 selection4";
const threshold = 2;
const pattern = /selection(\d+)/
const result = str
.split(' ')
.filter(x => Number(x.match(pattern)[1]) <= threshold)
.join(' ');
console.log(result);

JavaScript replace string and comma if comma exists else only the string

I got a string like:
var string = "string1,string2,string3,string4";
I got to replace a given value from the string. So the string for example becomes like this:
var replaced = "string1,string3,string4"; // `string2,` is replaced from the string
Ive tried to do it like this:
var valueToReplace = "string2";
var replace = string.replace(',' + string2 + ',', '');
But then the output is:
string1string3,string4
Or if i have to replace string4 then the replace function doesn't replace anything, because the comma doens't exist.
How can i replace the value and the commas if the comma(s) exists?
If the comma doesn't exists, then only replace the string.
Modern browsers
var result = string.split(',').filter( s => s !== 'string2').join(',');
For older browsers
var result = string.split(',').filter( function(s){ return s !== 'string2'}).join(',');
First you split string into array such as ['string1', 'string2', 'string3', 'string4' ]
Then you filter out unwanted item with filter. So you are left with ['string1', 'string3', 'string4' ]
join(',') convertes your array into string using , separator.
Split the string by comma.
You get all Strings as an array and remove the item you want.
Join back them by comma.
var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var parts = string.split(",");
parts.splice(parts.indexOf(valueToReplace), 1);
var result = parts.join(",");
console.log(result);
You only need to replace one of the two commas not both, so :
var replace = string.replace(string2 + ',', '');
Or :
var replace = string.replace(',' + string2, '');
You can check for the comma by :
if (string.indexOf(',' + string2)>-1) {
var replace = string.replace(',' + string2, '');
else if (string.indexOf(string2 + ',', '')>-1) {
var replace = string.replace(string2 + ',', '');
} else { var replace = string.replace(string2,''); }
You should replace only 1 comma and also pass the correct variable to replace method such as
var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var replaced = string.replace(valueToReplace + ',', '');
alert(replaced);
You can replace the string and check after that for the comma
var replace = string.replace(string2, '');
if(replace[replace.length - 1] === ',')
{
replace = replace.slice(0, -1);
}
You can use string function replace();
eg:
var string = "string1,string2,string3,string4";
var valueToReplace = ",string2";
var replaced = string.replace(valueToReplace,'');
or if you wish to divide it in substring you can use substr() function;
var string = "string1,string2,string3,string4";
firstComma = string.indexOf(',')
var replaced = string.substr(0,string.indexOf(','));
secondComma = string.indexOf(',', firstComma + 1)
replaced += string.substr(secondComma , string.length);
you can adjust length as per your choice of comma by adding or subtracting 1.
str = "string1,string2,string3"
tmp = []
match = "string3"
str.split(',').forEach(e=>{
if(e != match)
tmp.push(e)
})
console.log(tmp.join(','))
okay i got you. here you go.
Your question is - How can i replace the value and the commas if the comma(s) exists?
So I'm assuming that string contains spaces also.
So question is - how can we detect the comma existence in string?
Simple, use below Javascript condition -
var string = "string1 string2, string3, string4";
var stringToReplace = "string2";
var result;
if (string.search(stringToReplace + "[\,]") === -1) {
result = string.replace(stringToReplace,'');
} else {
result = string.replace(stringToReplace + ',','');
}
document.getElementById("result").innerHTML = result;
<p id="result"></p>

How to split two dimensional array in JavaScript?

I have string like below:
"test[2][1]"
"test[2][2]"
etc
Now, I want to split this string to like this:
split[0] = "test"
split[1] = 2
split[2] = 1
split[0] = "test"
split[1] = 2
split[2] = 2
I tried split in javascript but no success.How can it be possible?
CODE:
string.split('][');
Thanks.
Try this:
.replace(/]/g, '') gets rid of the right square bracket.
.split('[') splits the remaining "test[2[1" into its components.
var str1 = "test[2][1]";
var str2 = "test[2][2]";
var split = str1.replace(/]/g, '').split('[');
var split2 = str2.replace(/]/g, '').split('[');
alert(split);
alert(split2);
you can try :
string.split(/\]?\[|\]\[?/)
function splitter (string) {
var arr = string.split('['),
result = [];
arr.forEach(function (item) {
item = item.replace(/]$/, '');
result.push(item);
})
return result;
}
console.log(splitter("test[2][1]"));
As long as this format is used you can do
var text = "test[1][2]";
var split = text.match(/\w+/g);
But you will run into problems if the three parts contain something else than letters and numbers.
You can split with the [ character and then remove last character from all the elements except the first.
var str = "test[2][2]";
var res = str.split("[");
for(var i=1, len=res.length; i < len; i++) res[i]=res[i].slice(0,-1);
alert(res);

Categories

Resources