Related
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);
const str = ".1.2.1"
const str2 = ".1";
const func = (str, str2) => {
...
}
expected output = ".1.2"
Another example:
str = "CABC"
str2 = "C"
Expected output "CAB"
So the last part of the string that matches the end of the string should be removed.
Can this be done with some neat build-in-function in javascript?
Update
Updated string example. Simple replace does not work.
Just try replacing \.\d+$ with empty string, using a regex replacement:
var input = "1.2.1";
input = input.replace(/\.\d+$/, "");
console.log(input);
Edit:
Assuming the final portion of the input to be removed is actually contained in a string variable, then we might be forced to use RegExp and manually build the pattern:
var str = "CABC"
var str2 = "C"
var re = new RegExp(str2 + "$");
str = str.replace(re, "");
console.log(str);
You could create a regular expression from the string and preserve the dot by escaping it and use the end marker of the string to replace only the last occurence.
const
replace = (string, pattern) => string.replace(new RegExp(pattern.replace(/\./g, '\\\$&') + '$'), '')
console.log(replace(".1.2.1", ".1"));
console.log(replace("CABC", "C"));
You can check the position of the string to find using lastIndexOf and if it is at its supposed position, then just slice
function removeLastPart(str, str2)
{
result = str;
let lastIndex = str.lastIndexOf(str2);
if (lastIndex == (str.length - str2.length))
{
result = str.slice(0, lastIndex)
}
return result;
}
console.log(removeLastPart(".1.2.1", ".1"));
console.log(removeLastPart("CABC", "C"));
console.log(removeLastPart(" ispum lorem ispum ipsum", " ipsum"));
// should not be changed
console.log(removeLastPart("hello world", "hello"));
console.log(removeLastPart("rofllollmao", "lol"));
You can use String.prototype.slice
const str = "1.2.1"
const str2 = ".1";
const func = (str) => {
return str.slice(0, str.lastIndexOf("."));
}
console.log(func(str));
You could create a dynamic regex using RegExp. The $ appended will replace str2 from str ONLY if it is at the end of the string
const replaceEnd = (str, str2) => {
const regex = new RegExp(str2 + "$");
return str.replace(regex, '')
}
console.log(replaceEnd('.1.2.1', '.1'))
console.log(replaceEnd('CABC', 'C'))
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>
Strip the last hyphen(-) from phone number
I want 647-484-3839 to become 647-4843839
var phoneNumberInput = "647-484-3839";
var newStr = phoneNumberInput .replace(/[^-]+-$/,"");
You can:
var pos = phoneNumberInput.lastIndexOf("-");
phoneNumberInput = phoneNumberInput.substr(0, pos) + phoneNumberInput.substr(pos + 1);
Use positive look-ahead assertion to get - which doesn't follow string contains -.
var phoneNumberInput = "647-484-3839";
var newStr = phoneNumberInput.replace(/-(?=[^-]+$)/, "");
console.log(newStr);
Where [^-]+ matches any combination which doesn't include hyphen.
i have this string:
var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
how do i get digits 123456789 (between "d" and "?") ?
these digits may vary. the number of digits may vary as well.
How do i get them?? Regex? Which one?
try
'http://xxxxxxx.xxx/abcd123456789?abc=1'.match(/\d+(?=\?)/)[0];
// ^1 or more digits followed by '?'
Try
var regexp = /\/abcd(\d+)\?/;
var match = regexp.exec(input);
var number = +match[1];
Are the numbers always between "abcd" and "?"?
If so, then you can use substring():
s.substring(s.indexOf('abcd'), s.indexOf('?'))
If not, then you can just loop through character by character and check if it's numeric:
var num = '';
for (var i = 0; i < s.length; i++) {
var char = s.charAt(i);
if (!isNaN(char)) {
num += char;
}
}
Yes, regex is the right answer. You'll have something like this:
var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
var re = new RegExp('http\:\/\/[^\/]+\/[^\d]*(\d+)\?');
re.exec(s);
var digits = $1;