开发者

How do we trim text from arbitary start to arbitary end position?

开发者 https://www.devze.com 2023-03-21 19:55 出处:网络
How do I obtain a trimmed down inputted text ? eg, var txt = \"Hello, how are you???\"; To produce result like :

How do I obtain a trimmed down inputted text ? eg,

var txt = "Hello, how are you???";

To produce result like :

" how are you"

Here, I would like to remove the earlier "Hello," part and remove the later "???" part. I cannot directly use the character positions because it could be any word before com开发者_运维问答ma which user inputs.


You can remove everything up to the comma using a regular exprssion:

var txt = "Hello, how are you???";

alert(txt.replace(/^[^,]*,/,''));

You can remove any trailing question marks using:

var txt = "Hello, how are you???";

alert(txt.replace(/\?*$/,''));

and you can combine them using:

var txt = "Hello, how are you???";

alert(txt.replace(/(^[^,]*,)|(\?*$)/g,''));


You can use string.replace unction.

var txt = "Hello, how are you???";
txt = txt.replace('???', '');
txt = txt.replace('Hello,', '');
document.write(txt);
0

精彩评论

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