简体   繁体   English

使用javascript替换换行符和逗号

[英]replacing newline character and comma using javascript

I have script to fetch the address from the textbox and want to remove all the comma and newline character in the given address .I have tried using 2 methods but both methods are giving error .Please give some suggestion. 我有脚本从文本框中获取地址,并希望删除给定地址中的所有逗号和换行符。我尝试使用2种方法,但两种方法都出错,请提出一些建议。

Sample Code: 样例代码:

<textarea rows="3" cols="33" name="inc_Address" id="inc_address" required></textarea>

method1 方法1

<Script>
    function tidyAddress() {
        addrArray = document.getElementById('inc_address').value.split(" ");
        var addrArray2 = addrArray.replace(/\n|\r|,/g, "");
    }
</script>

method2 方法2

<Script>
    function trim(str) {
        return str.replace(/\n|\r|,/g, "");
    }

    function tidyAddress() {
        addrArray = document.getElementById('inc_address').value.split(" ");
        var addrArray2 = trim(addrArray);
    }
</script>

Giving error as Uncaught TypeError: addrArray.replace is not a function 给出错误为未捕获的TypeError:addrArray.replace不是函数

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. replace()方法在字符串中搜索指定的值或正则表达式,然后返回替换了指定值的新字符串。

You are using split() before that and it will return an array so you are getting error. 在此之前,您正在使用split() ,它将返回一个数组,因此会出现错误。

You should try : 你应该试试 :

var addrString = document.getElementById('inc_address').value;
addrString.replace(/\n|\r|,/g, " ");

You are trying to apply string functions on array 您正在尝试在数组上应用字符串函数

 addrArray.replace(/\n|\r|,/g, ""); \\ wrong => addrArray is a array not string

also

trim(addrArray)  \\ where trim() returns string not array

to replace the values from array 替换数组中的值

var result = [];
addrArray.forEach(function(value){
    result.push( value.replace(/[\n\r\,]+/g, ' ') );
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM