javascript中的字符串替换无法正常工作

时间:2016-02-22 14:41:53

标签: javascript php jquery

<?php
$str = "this is a . test . string.";
?>

<script>
    var str = '<?php echo $str; ?>';
    wordss = ' . ';
    var res = str.replace(new RegExp(wordss,"g"),". "); //space(.)space convert to (.)space
    console.log(res);
</script>

输出

this is. . test. string.

我希望它在“这是一个.test。字符串。

2 个答案:

答案 0 :(得分:2)

var str = "this is a . test . string.";
var res = str.split(" . ").join(". ");
console.log(res);

答案 1 :(得分:0)

使用RegExp /\s+(?=\.)/g匹配后跟.字符的空格字符

var str = "this is a . test . string."
str = str.replace(/\s+(?=\.)/g, "");
document.body.textContent = str;