[英]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? 我该如何实现?
You can use the replace function in Javascript. 您可以在Javascript中使用替换功能。
var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');
Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/ 这是jsfiddle: https ://jsfiddle.net/aoytdh7m/33/
You dont have to use arrays. 您不必使用数组。 Just do this 做这个
string[1] + string[0] + string.slice(2)
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;
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. 请注意,string [0]指向字符串中的第一个字符,string [1]指向第二个字符,依此类推,因为代码从0开始计数。
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;
let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.