0

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.

7
  • Maybe .replace(/[^,]*,/, "") will do? Why capture the rest with (.*)? Commented Feb 12, 2019 at 15:02
  • I tried that too, it didnt work either. Commented Feb 12, 2019 at 15:04
  • JQuery does not feature regex, the RegExp class is a JavaScript thing. You may run a regex replacement on strings. You need something like $('.class-name').text().replace(/.*,/, "") Commented Feb 12, 2019 at 15:05
  • But, there are lots of similar strings, cant do the string replacement for each and every string. Commented Feb 12, 2019 at 15:09
  • .replace(/[^,]+,(.*)/g,'$1') Commented Feb 12, 2019 at 15:12

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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

Like this:

Code pen example

Comments

0

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 (.*)

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.