neenkart
neenkart

Reputation: 156

How to use replace() to remove comma and strings before it with Jquery?

First of all I have searched the answer for my query and couldn't find any which using replace() function.

In the following string, Strada Genova 204, 10024 Moncalieri I need to replace comma and the string before it with null, so, the outpt will be just 10024 Moncalieri

I tried $('.class-name').replace(/[^\,]*,(.*)/, "") and didnt work. Changed the regex part several times and nothing worked.

Upvotes: 0

Views: 950

Answers (3)

Sam
Sam

Reputation: 89

Here is the solution to append new filtered text into the HTML element with a class name filtered

Note: Be sure to load jQuery from either locally or CDN.

HTML

<p class="class-name">Strada Genova 204, 10024 Moncalieri</p>
<p class="filtered"></p>

Javascript

$('.filtered').append($('.class-name').text().replace(/[\w\s]*,?\s?/, ""));

JS Fiddle => https://jsfiddle.net/sam1205/gqspwd0a/136/

Upvotes: 1

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

Try this:

var str="Strada Genova 204, 10024 Moncalieri";
console.log(str.replace(/[^,]+,(\s+)?(.*)/g,"$2"));

[^,]+ Every thing not including , then , then (\s+)? if any withespaces and finally captured part (.*)

Upvotes: 0

Refilon
Refilon

Reputation: 3489

You can also use split(',') and get the last element in the array.

Like this:

Code pen example

Upvotes: 0

Related Questions