Setting new value to str.charAt() [duplicate] - javascript

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 2 years ago.
I am trying to set the value of a character at a certain index in a string with a new character and I was wondering if it was possible with charAt() method. Something like this. str.charAt(1) will return string "e" at first.
let str = "hello";
str.charAt(1) = 'a';
str.charAt(1) will then return string "a".
My expected result is that the new string reads "hallo". But this results in an Uncaught ReferenceError: Invalid left-hand side in assignment. So is it simply not possible with this method?

charAt() is a function on String prototype,and you are trying to overriding it by that syntax; charAt() will return the character at the index and it is getter, not a setter; so you need to define your own custom method to achieve that, either by defining a pure function like snippet below or by defining it on String.prototype so you can use on any string;
let str = "hello";
function replaceStrAtIndex( str, index, letter ){
let modifiedStr = [...str];
modifiedStr[index] = letter;
return modifiedStr.join('')
}
console.log(replaceStrAtIndex(str, 1, 'a'))
or defining on string prototype:
String.prototype.replaceCharAt = function replaceStrAtIndex( index, letter ){
let modifiedStr = [...this];
modifiedStr[index] = letter;
return modifiedStr.join('')
}
let str = "hello";
console.log(str.replaceCharAt( 1, 'a'))

Related

change words at particular location in javascript string [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed last year.
var str = "Hello world";
str.charAt(2)="P"//instead of l i am assigning the value P
console.log(str)
I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string
You need to make an array out of the string to replace by index.
The following should do the trick.
const changeChar = (str, newValue, index) => {
let splitted = str.split("");
splitted[index] = newValue;
return splitted.join("");
}
In JavaScript, strings are immutable, there are 2 ways you can do this which I have mentioned below
1 way can be to split the string using two substrings and stuff the character between them
var s = "Hello world";
var index = 2;
s = s.substring(0, index) + 'p' + s.substring(index + 1);
console.log(s)
2 way can be to convert the string to character array, replace one array member and join it
var str="Hello World"
str = str.split('');
str[2] = 'p';
str = str.join('');
console.log(str)

Confused why my regex expression isn't working? [duplicate]

This question already has answers here:
Alternation operator inside square brackets does not work
(2 answers)
What's the difference between () and [] in regular expression patterns?
(6 answers)
Closed 3 years ago.
Attempting to create a regex expression that splits a string at ',' and '\n' and then a passed in custom delimiter (which is signified by firstChar in my code).
Format for the string being passed in: {delimiter}\n{numbers}. I've used regex101 online and it seems to work on there but in my actual code it doesn't split at the custom delimiter so not sure what I'm doing wrong.
if (str.includes('\n')) {
let firstChar = str.slice(0, 1);
if (parseInt(firstChar)) {
strArr = str.split(/,|\n/) ;
} else {
strArr = str.split(/[,|\n|firstChar]/);
}
}
expect ';\n2;5' to equal 7 but my array splits into [";", "2;5"] for some reason.
Your first character isn't a number so you go to else condition directly, if you want a dynamic regex then you need to build it using RegExp
Also you don't need character class here
/[,|\n|firstChar]/
it should be
/,|\n|firstChar/
let splitter = (str) => {
if (str.includes('\n')) {
let firstChar = str.slice(0, 1);
if (parseInt(firstChar)) {
return str.split(/,|\n/);
} else {
let regex = new RegExp(`,|\\n|\\${firstChar}`, 'g') // building a dynamic regex here
return str.split(regex).filter(Boolean)
}
}
}
console.log(splitter(";\n2;5"))
console.log(splitter("*\n2*5"))

toString not getting applied to mixture of numbers, characters and special symbols

I am trying below code:-
var testrename = {
check: function() {
var str = 988,000 PTS;
var test = str.toString().split(/[, ]/);
console.log(test[0] + test[1]);
}
}
testrename.check();
I want output as- 988000
I was trying it on node
Your str variable's assigned value needs to be quoted in order to assign a string value to it, and for it to be recognized as a string.
It looks like what you're trying to do is extract the integer value of a string, so return 988000 from the string "988,000 PTS", and you would use parseInt(string) for that.
Update: The comma will break the parseInt function and return a truncated number, (988 not 988000) so you can use the replace function with a regular expression to remove all non-numeric values from the string first.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var testrename={
check :function() {
var str ="988,000 PTS";
cleanStr = str.replace(/\D/g,'');
var test = parseInt(cleanStr);
console.log(test);
}
} testrename.check();

pass variable to replace function regular expression javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I want to have a 'newline'-function to pass a string to it and print it on pdf. my function so far is
var array = new Array();
function newLineFunction_PDF(text) {
var arr = text.replace(/.{70}\S*\s+/g, "$&#").split(/\s+#/);
return arr;
}
array = newLineFunction_PDF('some Text');
for( var i in array) {
print(array[i]);
}
What it does is cut the text in to pieces of length-70 incl. the last word, push it into the array and print it afterwards with new lines. Now i want to pass a number to the function, like 100, so i can decide the max-length of the text per line.
So far I tried:
function newLineFunction_PDF(text, num) {
var re = new RegExp(/.{num}\S*\s+/g);
var arr = text.replace(re, "$&#").split(/\s+#/);
return arr;
}
but I dont know how and where to add escapes into the new RegExp.
The parameter of Regexp is a string:
var re = new RegExp('.{' + num + '}\S*\s+', 'g');

jQuery multiple replace [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
I'm trying to remove the euro sign from my string.
Since the string looks like this €33.0000 - €37.5000, I first explode to string on the - after I try to remove the euro sign.
var string = jQuery('#amount').val();
var arr = string.split(' - ');
if(arr[0] == arr[1]){
jQuery(this).find('.last').css("display", "none");
}else{
for(var i=0; i< arr.length; i++){
arr[i].replace('€','');
console.log(arr[i]);
}
}
When I try it on my site, the euro signs aren't removed, when I get the string like this
var string = jQuery('#amount').val().replace("€", "");
Only the first euro sign is removed
.replace() replace only the fisrt occurence with a string, and replace all occurences with a RegExp:
jQuery('#amount').val().replace(/€/g, "")
Try using a regular expression with global replace flag:
"€33.0000 - €37.5000".replace(/€/g,"")
First get rid of the € (Globally), than split the string into Array parts
var noeur = str.replace(/€/g, '');
var parts = noeur.split(" - ");
The problem with your first attempt is that the replace() method returns a new string. It does not alter the one it executes on.
So it should be arr[i] = arr[i].replace('€','');
Also the replace method, by default, replaces the 1st occurrence only.
You can use the regular expression support and pass the global modifier g so that it applies to the whole string
var string = Query('#amount').val().replace(/€/g, "");
var parts = /^€([0-9.]+) - €([0-9.]+)$/.exec(jQuery('#amount').val()), val1, val2;
if (parts) {
val1 = parts[1];
val2 = parts[2];
} else {
// there is an error in your string
}
You can also tolerate spaces here and there: /^\s*€\s*([0-9.]+)\s*-\s*€\s*([0-9.]+)\s*$/

Categories