Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

jquery - How do I split a string at a space after a certain number of characters in javascript?

So I have a nice long string that I need to split in Javascript at a space following a certain amount of characters. For instance, if I have

"You is a dog and I am a cat."

and I want it to split after 10 characters but at the next space... so rather than splitting dog up I want the next space to be the split point.

I hope I wrote that clearly, its a bit awkward to explain.

EDIT: I need to store all of this into an array. So splitting the string up as I described, but storing it into an array which I can iterate through. Sorry for the confusion- like I said, a bit odd to describe.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Consider:

str = "How razorback-jumping frogs can level six piqued gymnasts!"
result = str.replace(/.{10}S*s+/g, "$&@").split(/s+@/)

Result:

[
 "How razorback-jumping",
 "frogs can level",
 "six piqued",
 "gymnasts!"
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...