user736893
user736893

Reputation:

What's wrong with my regex replace functions?

    var storeName = "St. Bob's Store";
    var storeId = storeName.replace(/./g,"").replace(/\s/g, '').replace(/'/g,"")
    $('#storeName').html(storeName)
    $('#storeId').html("(" + storeId + ")")
    
    console.log("Updating " + storeName + "(" + storeId + ")");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="storeName">Loading</div>
<div id="storeId">loading</div>

What am I doing wrong with storeId? It's empty.

Upvotes: 0

Views: 56

Answers (2)

Nineoclick
Nineoclick

Reputation: 814

If you want to match "dot" char, you have to escape it, like this:

var storeId = storeName.replace(/\./g,"").replace(/\s/g, '').replace(/'/g,"");

Here's a fiddle: https://jsfiddle.net/e63bq01L/

If not escaped, the dot matches all characters in a string.

Upvotes: 2

taxicala
taxicala

Reputation: 21769

You have to escape the dot character:

storeName.replace(/\./g,"").replace(/\s/g, '').replace(/'/g,"")

Otherwise, you will replace everything.

Upvotes: 2

Related Questions