1
var word = 'dumbways'
word.split()

so how to split a word to dumb and ways

I have tried by

var word= "dumbways";
var splitted = word.split('ways'); //this will output ["1234", "56789"]
var first = splitted[0];
var second = splitted[1];
console.log('First is: ' + first + ', and second is: ' + second);

but it doesn't work, it's only log 'dumb'

thank you

3
  • split it with character not with word. `word.split('w'); Commented Apr 18, 2020 at 10:17
  • 3
    That's because when you split something, it removes it. If i split '56,73' by a comma, it would output '56' and '73'. Commented Apr 18, 2020 at 10:17
  • @NajamUsSaqib so the it will log 'dumb' and 'ays' how to log 'dumb' and 'ways' Commented Apr 18, 2020 at 10:19

4 Answers 4

3

The split method searches for the string you specify in the argument, then uses it to split the original string around it.

Your case is a bit weird. First you need to search the word "ways", then you want to break the string at the point where that word has been found.

I'd write the code differently:

var word= "dumbways";
var pos = word.indexOf('ways');
var first = word.substring(0, pos);
var second = word.substring(pos);
console.log('First is: ' + first + ', and second is: ' + second);

You should also specify how the function should behave when the string won't be found.

Have a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Sign up to request clarification or add additional context in comments.

Comments

1

as mentioned in the comments the delimter will be removed from the result array, you can just have the string splitted twice like this:

var word= "dumbways";
var first = word.split('dumb')[1];
var second = word.split('ways')[0];
console.log(first);
console.log(second);

1 Comment

what's the purpose of filter? you can remove them.
0

You can use search:

let word = 'dumbways'
let index = word.search('ways')
let firstPart = word.substring(0, index)
let secondPart = word.substring(index)
console.log('firstPart:', firstPart, 'secondPart:', secondPart)

Comments

0

Your method won't work. Try something like this, perhaps:

var word = "dumbways"
var split = word.match(/[\s\S]{1,4}/g);
console.log(`First word: ${split[0]}. Second word: ${split[1]}`)

This splits the string every four characters, so it won't work for words with other lengths, but works in this situation.

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.