开发者

javascript spilt to get part of the word

开发者 https://www.devze.com 2023-04-03 00:30 出处:网络
I tried use javascript spilt to get part of the word : new from What#a_new%20day I tried code like this:

I tried use javascript spilt to get part of the word : new from What#a_new%20day

I tried code like this:

<script>
var word="What#a_new%20day";
var开发者_开发知识库 newword = word.split("%20", 1).split("_", 2);
alert(newword);
</script>

But caused:

Uncaught TypeError: Object What#a_new has no method 'split'

Maybe there have more wiser way to get the word which I need. So can anyone help me? Thanks.


split returns an array, so the second split is trying to operate on the array returned by the first, rather than a string, which causes a TypeError. You'll also want to add the correct index after the second call to split, or newword will also be an array, not the String you're expecting. Change it to:

var newword = word.split("%20", 1)[0].split("_", 2)[1];

This splits word, then splits the string at index 0 of the resulting array, and assigns the value of the string at index 1 of the new array to newword.


Regex to the rescue

var word="What#a_new%20day";
var newword = word.match(/_(.+)%/)[1];
alert(newword);

this returns the first ([1]) captured group ((...)) in the regex (_(.+)%) which is _ followed by any character (.) one or more times (+) followed by %.


the result of a split is an array, not a string. so what you need to do is

<script>
var word="What#a_new%20day";
var newword = word.split("%20", 1)[0].split("_", 2);
alert(newword);
</script>

notice the [0]


split returns an array: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

word.split("%20", 1);

gives an array so you cannot do :

(result from above).split("_", 2);


If split is what your after, go for it, but performance wise, it would be better to do something like this:

var word="What#a_new%20day";
var newword = word.substr(word.indexOf('new'),3)
alert(newword);

Live example: http://jsfiddle.net/qJ8wM/

Split searches for all instances of %20 in the text, whereas indexOf finds the first instance, and substr is fairly cheap performance wise as well.

JsPerf stats on split vs substring (a general case): http://jsperf.com/split-vs-substring

0

精彩评论

暂无评论...
验证码 换一张
取 消