BlogJava 首页 新随笔 联系 聚合 管理
  37 Posts :: 64 Stories :: 21 Comments :: 0 Trackbacks
Q
replace() 1
如何使用 replace() 来替换字符串中的字符。
replace() 2 - 全局搜索
如何使用 replace() 进行全局替换。
replace() 3 - 对大小写不敏感的搜索
如何使用 replace() 确保大写字母的正确性。
replace() 4
如何使用 replace() 来转换姓名的格式。
replace() 5
如何使用 replace() 来转换引号。
replace() 6
如何使用 replace() 把单词的首字母转换为大写。

实例

例子 1

在本例中,我们将使用 "W3School" 替换字符串中的 "Microsoft":

<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))
</script>

输出:

Visit W3School!

例子 2

在本例中,我们将执行一次全局替换,每当 "Microsoft" 被找到,它就被替换为 "W3School":

<script type="text/javascript">
var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School"))
</script>

输出:

Welcome to W3School! We are proud to announce that W3School
has one of the largest Web Developers sites in the world.

例子 3

您可以使用本例提供的代码来确保匹配字符串大写字符的正确:

text = "javascript Tutorial";
text.replace(/javascript/i, "JavaScript");

例子 4

在本例中,我们将把 "Doe, John" 转换为 "John Doe" 的形式:

name = "Doe, John";
name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");

例子 5

在本例中,我们将把所有的花引号替换为直引号:

name = '"a", "b"';
name.replace(/"([^"]*)"/g, "'$1'");

例子 6

在本例中,我们将把字符串中所有单词的首字母都转换为大写:

name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);

posted on 2009-09-10 10:38 xiachang88 阅读(255) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: