简体   繁体   English

Javascript正则表达式空白替换

[英]Javascript Regex Whitespace Replacement

I am trying to get the value of an <select></select> tag as set from the selected <option> value and replace any whitespace in the value with a dash. 我试图从选定的<option>值中获取设置的<select></select>标记的值,并将该值中的任何空格替换为破折号。 at the moment I am just then console.log() the value for testing but for some reason instead of selecting whitespace it is selecting and replacing lower case "s". 目前,我只是console.log()的测试值,但由于某种原因而不是选择空格,而是选择并替换小写的“ s”。 The code I am using is: <select onchange='var cat = this.value; var modi = cat.replace(/\\s/g , "-"); console.log(modi);'> 我正在使用的代码是: <select onchange='var cat = this.value; var modi = cat.replace(/\\s/g , "-"); console.log(modi);'> <select onchange='var cat = this.value; var modi = cat.replace(/\\s/g , "-"); console.log(modi);'>

Example: for example assume the this.value is equal to "test value" 示例: 例如,假设this.value等于“测试值”

Output: te-t value Expected Output: test-value 输出:te-t值预期输出:测试值

尝试这个

cat.split(" ").join("-");

 var str = "test value"; str = str.replace(/ /g,"-"); alert(str); 

试试这个方法

var reg = new RegExp(" ","g");

Try this 尝试这个

function myFunction() {
        var str = "Is this all there is?";
        var patt1 = / /g;
        var result = str.replace(patt1,"-");            
    }

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

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