javascript remove a exact index character from the string [duplicate] - javascript

This question already has answers here:
Remove a character at a certain position in a string - javascript [duplicate]
(8 answers)
Closed 1 year ago.
let test = 'This is the test string';
console.log(test.substr(3));
console.log(test.slice(3));
console.log(test.substring(3));
Theese methods are removing first 3 character. But i want to remove only third character from the string.
The log has to be: ' Ths is the test string'
İf you help me i will be glad. All examples are giving from the substr, slice eg. eg. Are there any different methods?

First, get the first 3 chars, then add chars 4-end, connect those to get the desired result:
let test = 'This is the test string';
let res = test.substr(0, 2) + test.substr(3);
console.log(res);
Since substr uses the following parameters
substr(start, length)
Start The index of the first character to include in the returned substring.
Length Optional. The number of characters to extract.
If length is omitted, substr() extracts characters to the end of the string.
We can use test.substr(3) to get from the 3'th to the last char without specifying the length of the string

const test = 'This is the test string';
const result = test.slice(0, 2) + test.slice(3);
console.log(result);
You can achieve this by concatenating the two parts of the string, using .slice().

You can achieve it using substring method and concatenating the strings
str = "Delete me ";
function del_one_char(string , removeAt){
return string.substring(0, removeAt) + string.substring( removeAt + 1, string.length);
}
console.log(del_one_char(str , 2))
// result one character at 2nd position is deleted

Related

Explain Javascript RegExp Behaviour [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 1 year ago.
I have this simple code:
let arr = [
'bill-items',
'bills',
'customer-return-items',
'customer-returns'
]
let re = new RegExp('^b*')
arr.forEach((e) => {
console.log(`Matching ${e}: ` + re.test(e))
})
I expect two matches and two non-matches. Strangely I get four matches!
Check here: https://jsfiddle.net/kargirwar/gu7Lshnt/9/
What is happening?
Try removing the "*" as following code snippets
"*" matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
let arr = [
'bill-items',
'bills',
'customer-return-items',
'customer-returns',
'when-b-is-not-the-first-character',
'b',
'' //empty string
]
let re = new RegExp('^b')
arr.forEach((e) => {
console.log(`Matching ${e}: ` + re.test(e))
})
The above code will match any strings that starts with letter b
It's quite simple
^. matches the beginning of the string. Each of the four strings has a beginning
b* matches any number of b also zero
And so, the regex matches the biggest part of the string it can. This is ^b for the first two strings and just ^ for the others.
If you want to match only strings that begin with at least one b use /^b+/ as the + requires at least one occurrence.
BTW you can use for instance https://regex101.com/ to test your regex and visualize the matches.

Re-replacing in regex [duplicate]

This question already has answers here:
Regex matching 5-digit substrings not enclosed with digits
(2 answers)
Closed 2 years ago.
I am creating a function that replaces the string with a
~(number)~.
Now let's say I have a string that says
This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2
I want to replace all the 2 in a string with ~86~ but when I am doing so the 2 in ~26~ and ~524~ also getting replaced to ~~86~6~ and ```~5~86~4~.
function replaceGameCoordinate() {
var string = `This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2`
var replaceArr = ['2'];
let patt = new RegExp(`${replaceArr[0]}`, 'gm')
var newString = string.replace(patt, "~86~");
console.log(newString);
}
replaceGameCoordinate();
The expected output should be :
This is the replacement of ~26~ and ~524~. We still have ~86~ cadets left. Have~86~go for the next mission.~86~
So you need a different regex rule. You don't want to replace 2. You want to replace 2 when it's not next to another number or ~.
In order to do this, you can use lookaheads and lookbehinds (although lookbehinds are not yet supported by regexes in JS, I believe, but at least with lookaheads) :
const input = "This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2";
const regex = /2(?![\d~])/gm // Means : "2 when it's not followed by a digit \d or a ~"
console.log( input.replace(regex, "~86~" ) )

Remove certain re-occurring characters from a string

I am quite new to JS and i have a problem:
I am trying to compare a string (as integer) with an input (as integer). The problem occurs because, the string is written as 10'000'000 for e.g. and the integer as 10000000, with 4 possible scenarios:
- 1'000'000
- 10'000'000
- 100'000'000
- 1'000'000'000
That is, the number (as string) can be from 1 million to 1 billion.
I want to erase (or replace with "") all of my " ' " characters so that the format which i will get for the string will be the same as the one of the integer
E.g. Integer: 95500000 String: 95'500'000 ---> need it to be 95500000
A similar solution but not quite the same is provided here:
Regex remove repeated characters from a string by javascript
String: 95'500'000 ---> need it to be 95500000
That’s as simple as "95'500'000".replace(/'/g, '')
g modifier makes it replace all occurrences, and not just the first one.
const str = "9'0'0000"
const removedSlashStr = str.split('').reduce((removedSlash, char) => {
if(char !== "'") removedSlash+=char
return removedSlash
}, '')
console.log(removedSlashStr) // "900000"

replace Nth occurence in string - JavaScript [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 9 years ago.
I'm sure this was supposed to work, but I can't get it doing what I want it to:
new_str = old_str.replace(3, "a");
// replace index 3 (4th character) with the letter "a"
So if I had abcdef then above should return abcaef but I must have gotten something wrong. It is changing characters, but not the expected ones.
Either native JS or jQuery solution is fine, whatever is best (I'm using jQuery on that page).
I've tried searching but all tutorials talk of Regex, etc. and not the index replace thing.
You appear to want array-style replacement, so convert the string into an array:
// Split string into an array
var str = "abcdef".split("");
// Replace char at index
str[3] = "a";
// Output new string
console.log( str.join("") );
Here are three other methods-
var old_str= "abcdef",
//1.
new_str1= old_str.substring(0, 3)+'a'+old_str.substring(4),
//2.
new_str2= old_str.replace(/^(.{3}).(.*)$/, '$1a$2'),
//3.
new_str3= old_str.split('');
new_str3.splice(3, 1, 'a');
//return values
new_str1+'\n'+new_str2+'\n'+ new_str3.join('');
abcaef
abcaef
abcaef

How can I get the last character in a string? [duplicate]

This question already has answers here:
How can I get last characters of a string
(25 answers)
Closed 10 years ago.
If I have the following variable in javascript
var myString = "Test3";
what is the fastest way to parse out the "3" from this string that works in all browsers (back to IE6)
Since in Javascript a string is a char array, you can access the last character by the length of the string.
var lastChar = myString[myString.length -1];
It does it:
myString.substr(-1);
This returns a substring of myString starting at one character from the end: the last character.
This also works:
myString.charAt(myString.length-1);
And this too:
myString.slice(-1);
var myString = "Test3";
alert(myString[myString.length-1])
here is a simple fiddle
http://jsfiddle.net/MZEqD/
Javascript strings have a length property that will tell you the length of the string.
Then all you have to do is use the substr() function to get the last character:
var myString = "Test3";
var lastChar = myString.substr(myString.length - 1);
edit: yes, or use the array notation as the other posts before me have done.
Lots of String functions explained here
myString.substring(str.length,str.length-1)
You should be able to do something like the above - which will get the last character
Use the charAt method. This function accepts one argument: The index of the character.
var lastCHar = myString.charAt(myString.length-1);
You should look at charAt function and take length of the string.
var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));

Categories

Resources