Shaonline
Shaonline

Reputation: 1637

how can i replace first two characters of a string in javascript?

lets suppose i have string

var string = "$-20455.00"

I am trying to swap first two characters of a string. I was thinking to split it and make an array and then replacing it, but is there any other way? Also, I am not clear how can I achieve it using arrays? if I have to use arrays.

var string = "-$20455.00"

How can I achieve this?

Upvotes: 9

Views: 47612

Answers (6)

Satyapriya Mishra
Satyapriya Mishra

Reputation: 130

let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result

Upvotes: 0

Kousi
Kousi

Reputation: 460

var string = "$-20455.00";
// Reverse first two characters
var reverse = string.slice(0,2).split('').reverse().join('');
// Concat again with renaming string
var result= reverse.concat(string.slice(2));

document.body.innerHTML = result;

Upvotes: 0

Ben Quigley
Ben Quigley

Reputation: 727


try using the "slice" method and string concatenation:

stringpart1 = '' //fill in whatever you want to replace the first two characters of the first string with here
string2 = stringpart1 + string.slice(1)

edit: I now see what you meant by "swap". I thought you meant "swap in something else". Vlad's answer is best to just switch the first and the second character.

Note that string[0] refers to the first character in the string, and string[1] to the second character, and so on, because code starts counting at 0.

Upvotes: 2

Vlad Ankudinov
Vlad Ankudinov

Reputation: 2046

You dont have to use arrays. Just do this

string[1] + string[0] + string.slice(2)

Upvotes: 13

Khalid Amiri
Khalid Amiri

Reputation: 421

You can use the replace function in Javascript.

var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');

Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/

Upvotes: 27

adeneo
adeneo

Reputation: 318182

You can split to an array, and then reverse the first two characters and join the pieces together again

var string = "$-20455.00";
    
var arr = string.split('');
    
var result =  arr.slice(0,2).reverse().concat(arr.slice(2)).join('');

document.body.innerHTML = result;

Upvotes: 3

Related Questions