Reputation: 13
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
Upvotes: 1
Views: 160
Reputation: 305
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.
Upvotes: 0
Reputation: 11622
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);
Upvotes: 1
Reputation: 3978
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)
Upvotes: 0
Reputation: 7304
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
Upvotes: 3