在javascript中混合字符串的中间部分 [英] Mixing up the middle of strings in javascript

查看:110
本文介绍了在javascript中混合字符串的中间部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种雄辩的方式来混合字符串中的字词的中间字符,如这是一个字符串示例变成这是一个eplamxe sritng。
我想先把单词分成一个数组,选择长于两个字符的单词,把第一部分的第一个和最后一个字母分开,但我找不出一个好的方法来争夺它们。 / p>

解决方案

  function middleMix(s){
var A = s.split ''),c1 = A.shift(),c3 = A.pop()|| ; (A.length)c1 + = A.splice(Math.floor(Math.random()* A.length),1);
返回c1 + c3;





$ b

这种方法将字符串拆分为一个字符数组,将第一个字符并弹出最后一个。



然后拼接中间部分(如果有),每次一个随机字符,并添加到前缀中。 b
$ b

返回最后加后缀。

// edit- multiple words

  function middleMix(str){
var s = str.split('');
for(var i = 0; i var A = s [i] .split(''),c1 = A.shift(),c3 = A. pop()|| ; (A.length)c1 + = A.splice(Math.floor(Math.random()* A.length),1);
s [i] = c1 + c3;
}
return s.join('');
}

middleMix(这是一个示例字符串)

/ *返回值:(字符串)
tihs是一个exmlpae sitrng
* /


I'm looking for an eloquent way to mix up the middle characters of words in a string, as in "this is an example string" becomes "tihs is an eplamxe sritng." I'm thinking first separate the words into an array, select words longer than two characters, separating out the first and last letters for the first part, but I can't figure out a good way to scramble them.

解决方案

function middleMix(s){
    var A= s.split(''), c1= A.shift(), c3= A.pop() || '';
    while(A.length) c1+= A.splice(Math.floor(Math.random()*A.length), 1);
    return c1+c3;
}

This method splits the string into an array of characters, shifts off the first character and pops off the last.

The middle part(if any) is then spliced, one random character at a time, and added to the prefix.

It is returned with the suffix added last.

//edit- multiple words

function middleMix(str){
    var s= str.split(' ');
    for(var i= 0; i<s.length;i++){
        var A= s[i].split(''), c1= A.shift(), c3= A.pop() || '';
        while(A.length) c1+= A.splice(Math.floor(Math.random()*A.length), 1);
        s[i]= c1+c3;
    }
    return s.join(' ');
}

middleMix("this is an example string")

/*  returned value: (String)
tihs is an exmlpae sitrng
*/

这篇关于在javascript中混合字符串的中间部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆