replace Nth occurence in string - JavaScript [duplicate] - javascript

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

Related

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

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

Javascript split with regular expression return empty values [duplicate]

This question already has answers here:
javascript regex split produces too many items
(4 answers)
Closed 3 years ago.
Hi I have to split a string in two parts, the first one is always a char the second one is a number.
i.e.
a12
c4
I try to use this expression:
var myString = 'a12';
var mySplits = myString.split(/^([a-zA-Z]{1,2})([0-9]{1,2})$/);
console.log(mySplits);
the array expected is:
["a", "12"]
the result instead is:
["", "a", "12", ""]
I don't understand the reason why the result array has an empty value at start and at end.
Any help is really appreciated.
UPDATE
the solution proposed works but we can use a more elegant way.
ES18
With ES18 we could use the group capturing name
var myString = 'a12';
var matches =
/^(?<letter>[a-zA-Z]{1,2})(?<number>[0-9]{1,2})$/.exec(myString).concat();
console.log(matches.groups.letter);
console.log(matches.groups.number);
ES10
ES10 added the method .matchAll() that returns an Iterator, so if the need is not capture a single value but capture globally this method can be useful.
var myString = 'a12 b12 ';
for (const match of myString.matchAll(/(?<letter>[a-zA-Z]{1,2})(?<number>[0-9]{1,2})/g)) {
console.log(match.groups.letter);
console.log(match.groups.number);
}
var myString = 'a12';
var list = /^([a-zA-Z]{1,2})([0-9]{1,2})$/.exec(myString).concat();
list.shift(); // remove the first element
console.log(list); //This is the list that you want

Take the first letters of a string splitted by white space [duplicate]

This question already has answers here:
Get first letter of each word in a string, in JavaScript
(20 answers)
Closed 4 years ago.
I have a string like this:
DEBIT CARD. How can I extract the first letters of this string which is splitted by white space? To be more specific, I want the D and C parts of this string.
Use charAt(0) along with split():
split(/\s+/) will split the string into array structure based on whitespaces(single or multiple) so that you can loop over the elements of the array using map() and get the first character for each element. Then, finally you need to join('') the array and get the string representation.
var str = 'DEBIT CARD';
var res = str.split(/\s+/).map(x=>x.charAt(0)).join('');
console.log(res);
var stringg = 'DEBIT CARD';
var out = stringg.split(' ');
var required = out[1][0]; /* it will return only `C`, if you want the
first character of all letters just loop on `out` and get 0 index,
Here you can also use each loop or map and join functions to
achieve desired output.*/
console.log(required);

How do I insert something at a specific character with Regex in Javascript [duplicate]

This question already has answers here:
Simple javascript find and replace
(6 answers)
Closed 5 years ago.
I have string "foo?bar" and I want to insert "baz" at the ?. This ? may not always be at the 3 index, so I always want to insert something string at this ? char to get "foo?bazbar"
The String.protype.replace method is perfect for this.
Example
let result = "foo?bar".replace(/\?/, '?baz');
alert(result);
I have used a RegEx in this example as requested, although you could do it without RegEx too.
Additional notes.
If you expect the string "foo?bar?boo" to result in "foo?bazbar?boo" the above code works as-is
If you expect the string "foo?bar?boo" to result in "foo?bazbar?bazboo" you can change the call to .replace(/\?/g, '?baz')
You don't need a regular expression, since you're not matching a pattern, just ordinary string replacement.
string = 'foo?bar';
newString = string.replace('?', '?baz');
console.log(newString);

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