如何使用 JavaScript 删除字符串中除数字和空格之外的所有特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19921844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove all special characters except numbers and space in a string using JavaScript?
提问by Chandrakanth Gowda
I'm developing a Phonegap Android application. Now I want to pass some parameters from one page to another html page. I'm not using any server side methods. In the second page I want to get all passed parameters from first page using JavaScript.
我正在开发一个 Phonegap Android 应用程序。现在我想将一些参数从一个页面传递到另一个 html 页面。我没有使用任何服务器端方法。在第二页中,我想使用 JavaScript 从第一页获取所有传递的参数。
For example here is an URL:
例如这里是一个 URL:
file:///C:/Users/dell/Projects/testapp1/search_result.html?searchstr=word1+*%26^+word2+3+word3+%40%23&city=city&showdishesnearby=false
file:///C:/Users/dell/Projects/testapp1/search_result.html?searchstr=word1+*%26^+word2+3+word3+%40%23&city=city&showdishesnearby=false
The below function used to extract each parameters values:
以下函数用于提取每个参数值:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function (m, key, value) {
vars[key] = value;
});
return vars;
}
searchString = getUrlVars()["searchstr"]; // this is how I call above function to get value of passed particular parameter
Now I want to remove all special characters except numbers and white space in variable searchString
.
现在我想删除变量中除数字和空格之外的所有特殊字符searchString
。
I have used the below code:
我使用了以下代码:
searchString = searchString.replace(/[^a-zA-Z ]/g, " ");
but that doesn't solve my problem. How to remove all special characters except numbers and space in a string using JavaScript?
但这并不能解决我的问题。如何使用 JavaScript 删除字符串中除数字和空格之外的所有特殊字符?
回答by OGHaza
searchString.replace(/[^a-z\d\s]+/gi, "");
removes all but letters, numbers and whitespace.
删除除字母、数字和空格之外的所有内容。
var s = 'keep%8$this part 3£$@plz £$% @£';
s.replace(/[^a-z\d\s]+/gi, "");
// "keep8this part 3plz "
回答by Satyendra Pandit
Simply add below code to replace all alpha-numeric character(punctuation, pace, underscore)
只需添加以下代码即可替换所有字母数字字符(标点、速度、下划线)
var string = str.replace(/[^A-Za-z0-9]/g,"")