-1

I need to get a id from a html element and replace a part of the word. For example:

HTML

<input type="checkbox" id="facebookCheckbox"></div>

JavaScript

var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");

This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?

I'm looking for purely javascript no jQuery

Thank you!

4

3 回答 3

2
name.replace("Checkbox","");

这显然不起作用,因为替换词必须是独立的才能被替换。

不,它确实有效,并且不需要“独立” - 字符串的任何部分都可以匹配。只有你对操作的结果什么也没做:

console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
于 2013-08-01T03:03:55.763 回答
0

替换时您正在创建字符串的副本,因此您必须将.replace()返回的结果分配给x.id.

var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
于 2013-08-01T03:02:39.020 回答
0

这不会以这种方式工作。但是,您可以使用一种标记类型的字符,通过它您可以将名称分解为数组并实现逻辑。例如:

var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");

//Now you have Checkbox and Facebook as string objects (part of array) and you can use them

name=arr[0]

我希望它能解决目的。

于 2013-08-01T03:12:46.500 回答