Change characters in a string by slicing in Javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a little question. Can i in javascript use string.slice() = x?
Example: "Hello world!".slice(2,3) --> = x <-- can I use this?
^ the 3rd character in the string
So, can i change characters with a slice? (:

No, you can not assign a value to a part of a string:
Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string.
You can split the string into an array of characters, change the wanted character at the given index and join the array for a new string.
var string = "Hello world!",
array = string.split('');
array[2] = 'X';
string = array.join('');
console.log(string);

Yes you can use slice to get the character.
var x = "Hello world!".slice(2,3);
console.log(x);
However, you can't change character with a slice. See Nina's answer how to do that.

Related

Format Number With Commas [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have built a function that formats a number using commas, similar to what the toLocaleString method does. To achieve that, I used a regular expression and recursion. However, I have a feeling that this could've been done better.
I did some research but was not able to find the answer I'm looking for. So, my question is...Is there a better way to do this?
function transform(value) {
const pureNumber = parseInt(value);
const numberParts = [];
function format(val) {
let formatted = val.toString().split(/(\d{3})$/).filter(i => !!i).join(",");
const splitted = formatted.split(",");
if(splitted.length > 1){
numberParts.unshift(splitted[1]);
return format(splitted[0]);
}
numberParts.unshift(splitted[0]);
return numberParts.join(",");
}
return format(pureNumber.toString());
}
const data = "1234567890";
const result = transform(data);
console.log(result);
What I need you to note is that I used a regular expression to split the string, however, I was wondering if there is a way to only use regular expressions to avoid the recursion? I.e., Is there a way to use the regular expression starting at the end of the string and repeating towards left?
This can be accomplished much simpler using a single Regex expression:
function transform(value) {
return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// Works with string
console.log(transform("0123456789"));
// And numbers
console.log(transform(1234567890));
This regex will look in the string for any point that has 3 digits in a row after it and will make sure that point only has exactly multiples of 3 digits.
This was discovered in the first part of a post:
How to print a number with commas as thousands separators in JavaScript

how string.slice(0, -1) works for a string in javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I know that in string with name example example.slice(0, -1) it removes last character from it.
How does it do that? How slice(0, -1) removes last character from a string?
Because it is by the definition.
A negative index can be used, indicating an offset from the end of the sequence.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
It works like length of the string is given to second parameter.
const s = 'abcdefg'
console.log(s.slice(0, -1 + s.length))
// abcdef
console.log(s.slice(0, -1))
// abcdef

how to get all number from beginning of string until first non-number? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How to get all number from beginning of string until first non-number?
For example, I want to get 12345 from '12345abc' and another example get 5678 from '5678kkk'.
Is any way can do this?
You could use RegExp#match with ^ anchor, to find out the numeric characters from beginning:
const string = "12345abc";
const matches = string.match(/^\d+/);
// Fallback if no matches found
const numbers = (matches || [])[0];
console.log(numbers);
Use parseInt() as it will stripe out all the characters other than the numeric character so you do not need custom logic for getting the numeric value as you have described:
console.log(parseInt('12345abc'));
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Use parseInt
let str = '5678kkk';
console.log(parseInt(str));

Match 11 or 13 digits using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am writing a code where I am receiving a number of exactly 11 or 13 digits in it. But, the problem is that it may contain some hyphens at random places.
Can anyone suggest a regular expression for this?
Sample inputs (assuming only 5 digits):
1. 12345
2. 1-234-5
3. 12-34-5
4. 123-45
5. 1-2-34-5
Try this code snippet. It may help you.
var str="123-45";
str.replace( /\D+/g, '');
Here,
\D - Find a non-digit character.
so, Code will replace non-digit with ''.
It would be significantly easier, and infinitely more readable to remove all dashes, and then count the remaining characters.
var str = "1-234-5";
var res = str.replace(/-/g, '').length;
if(res === 11 || res === 13) {
//do whatever
}
Have a try with:
^(?:-?\d){11}(?:-?\d-?\d)?$
or, if - can't be in first place:
^(?:\d-?){11}(?:\d-?\d)?$

How do I tell what index a letter is in a string? (In Python, JS, Ruby, PHP etc...) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know that:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
print alphabet[0]
# prints a
print alphabet[25]
#prints z
and so on, but how do I find out the opposite, ie. :
alphabet = 'abcdefghijklmnopqrstuvwxyz'
's' = alphabet[?]
""" The question mark represents that I want to know
what index the letter is in the string."""
In python you could use the find method:
>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> alphabet.find('a')
0
>>> alphabet.find('b')
1
>>> alphabet.find('c')
>>> alphabet.find('z')
25
Edit to add: Like Warren pointed out you can also use index, the difference being that find will return -1 for the position if not found, and index raises a ValueError when not found.
In javascript, use indexOf:
> "abc".indexOf("b")
1
In javascript, you would use alphabet.indexOf('a').
In Python, to get the position of a certain character inside a string, it would be:
alphabet.index('s')
If you just want to get alphabet indices, this works (Python):
import string
for c in string.ascii_lowercase:
print(ord(c)-97)
This will print the numbers 0-25. The idea here is to make use of unicode points of the char using ord. lowercase chars starts at 97. Another example:
>>> ord('k')-97
10

Categories