Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 812
Shaonline Avatar asked Feb 18 '16 16:02

Shaonline


People also ask

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.

How do you replace the first occurrence of a character in a string?

Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced.

How do you replace a specific character in a string?

Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


2 Answers

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/

like image 179
Khalid Amiri Avatar answered Oct 21 '22 23:10

Khalid Amiri


You dont have to use arrays. Just do this

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

like image 11
Vlad Ankudinov Avatar answered Oct 21 '22 23:10

Vlad Ankudinov