1
<?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>

Output

this is. . test. string.

I want it in "this is a. test. string."

3
  • var res = str.replace(/ \. /g, ". "); - you have to quote the . character, and it's easier to use regex literals. Commented Feb 22, 2016 at 14:43
  • 1
    Also, you will want to do: var str = <?php echo json_encode($str); ?>; to avoid special characters from spilling over into your JavaScript. Commented Feb 22, 2016 at 14:44
  • how can i use a variable because i want to check multiple values Commented Feb 22, 2016 at 14:50

2 Answers 2

3
var str = "this is a . test . string.";
var res = str.split(" . ").join(". ");
console.log(res);
Sign up to request clarification or add additional context in comments.

Comments

0

Use RegExp /\s+(?=\.)/g to match space character that is followed by . character

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.