0

split string only when two or more spaces occurs.

string="Talk Talk  Walk Walk         sell sell";

Expected Result after split:

string[0]='Talk Talk';
string[1]='Walk Walk';
string[2]='sell sell';

Thanks

1
  • Prepare for a lot of regex solutions Commented Dec 23, 2013 at 7:38

4 Answers 4

2

You can use the regular expression /\s{2,}/, which means that, if there are 2 or more white space characters, split the string there.

myString="Talk Talk  Walk Walk         sell sell";
console.log(myString.split(/\s{2,}/));

Output

[ 'Talk Talk', 'Walk Walk', 'sell sell' ]
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

var str="Talk Talk  Walk Walk         sell sell";
var s = str.replace(/ {2,}/g,";").split(';');

Comments

0

Try this if not using RegEx.

var myString = "Talk Talk  Walk Walk         sell sell";
var result = myString.split("  ");

for (var i = result.length - 1; i >= 0; i--) {
    if (result[i] === "") {
        result.splice(i, 1);
    }
}

The result variable will have an array of split values.

1 Comment

You might want to trim the resultant elements. "a b".split(two_spaces) yields ["a", " b"]. Then, you'd have to remove empty elements.
0

Try this simple way:

var x = str.split(" +");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.