String Remove in Jquery - javascript

I want to remove - from a string
myString = 12-132-232-1213-3
I have already tried
myString.replace('-','');
But this would replace only the first charcter 12132-232-1213-3, but iam expecting 1213223212133 how to fix this?

You can specify it using the pattern /-/ with the global modifier g as follows:
myString.replace(/-/g, '');
// => "1213223212133"

This is because you have not assigned the value. Try like this and let me know.
myString = myString.replace('/-/g','');

There is two methods for remove/replace string in jQuery.
var myString = "12-132-232-1213-3";
1 myString = myString.replace('-','').replace('-','').replace('-','').replace('-','');
Here you can see .replace('-','') is use four times because we want to replace four times - in your string.
2 myString = myString.replace(/-/g,''); is more reliable to first one.
After see both method then most usefull mothod is 2. Because there is no repeated code for replace('-','')

Related

regex target specific character around variable

Hi,
I have this code:
var room = 'room2';
var exitroom = 'room1,room2,room3';
exitroom = exitroom.replace(/,${room},/,'');
console.log(exitroom);
you can try it here: https://jsfiddle.net/uq9w0Ls4/
my expected output is simply room1,room3 by taking room2 out but since it may change its position within the string I want to target the , no matter if it comes before or after the string but I cant figure out the regex logic here. I know I could just do simply:
var room = 'room2';
var exitroom = 'room1,room2,room3';
exitroom = exitroom.replace(room+',','').replace(','+room,'');
console.log(exitroom);
which works but I think regex would be a more direct approach.
Thank you.
First, by writing .replace(/,${room},/,'') you are not using the variable room.
To use a variable in a regex you should call new RegExp()
Second, if you want a regex that will match when the comma is before or after the word, you can use a group () with an Or | operator.
so it should look like this:
var reg = new RegExp(`(?:${room},|,${room})`, "g");
exitroom.replace(reg,'');
The ?: at the beginning of the group, is just so it should be a non-capturing group, it should work just fine also without it

Javascript replace first letter of every string?

I am trying to make a script that should replace strings. This is what my current replace function does:
let message2 = message1.replace(/hello/g, "[size=medium]h[/size]ello");
As you can see, this adds the size=medium tag to the h of the word. This works good, but I want this to work in every possible capitalization and still remain in that capitalization.
For example:
"hELLo" should be replaced with "[size=medium]h[/size]ELLo"
and
"HELLo" be replaced with "[size=medium]H[/size]ELLo"
Only the h/H should be wrapped in the tag, but I am not sure how to perform something like this. Big thanks for any input on this!
You can use capture groups:
message1.replace(/(h)(ello)/ig, "[size=medium]$1[/size]$2")
Or alternatively, look-ahead:
message1.replace(/h(?=ello)/ig, "[size=medium]$&[/size]")
You can try this regex:
var a = 'hello';
var b = 'HEllo';
console.log(a.replace(/^h/i, "[size=medium]$&[/size]"))
console.log(b.replace(/^h/i, "[size=medium]$&[/size]"))
Of if you just want to replace h in hello, you can use look ahead:
var a = 'HEllo';
var b = 'Halo';
console.log(a.replace(/^h(?=ello)/i, "[size=medium]$&[/size]"))
console.log(b.replace(/^h(?=ello)/i, "[size=medium]$&[/size]"))

Change a unique Character on jQuery

<span class="number1">10.00</span>
simply, i want to replace the '.'(dot) for a ','(comma) using jQuery.
I've tried several forms to search the $('.number1') characters and replacing
it with a comma.
<span class="number1">10.00</span>
What if there is more than one Dot in the string?
Why use jQuery for such a simple operation? What you need is a simple string manipulation. Adding a library so that you can type a few less characters to do something so basic seems hardly worth it.
What you really need the the plain old JavaScript String.replace() method.
Here's jQuery and non-jQuery ways to do it:
// With jQuery:
console.log($(".number1").text().replace(".", ","));
// Without jQuery:
console.log(document.querySelector(".number1").textContent.replace(".", ","));
// When you need to replace all the . chars. in the string, you'll need to use
// a regular expression with .replace().
// The / / denote the delimiters of a regular expression
// The \. is the escape code for a .
// The g means do a global find/replace throughout the string
// With jQuery:
console.log($(".number1").text().replace(/\./g, ","));
// Without jQuery:
console.log(document.querySelector(".number1").textContent.replace(/\./g, ","));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="number1">10.00.00</span>
Try this answer.
$(".number1").text(function () {
return $(this).text().replace(/\./g, ",");
});
this is a solution in vanilla js:
let spanNumber = document.querySelector('.number1')
let number = spanNumber.textContent
let newNumber = number.split('.').join(',')
spanNumber.innerHTML = newNumber
short version with replace:
let DOMElement = document.querySelector('.number1')
let string = DOMElement.textContent.replace('.',',')
DOMElement.innerHTML = string
Just use built in DOM property innerHTML, instead of unecessary jQuery mambo jambo like:
var num1 = document.querySelector('.number1');
num1.innerHTML = num1.innerHTML.replace('.', ',');
InnerHTML is value between your HTML tags, and since its a string it has access to all String prototype methods and properties.
Just turn it to array by finding a dot delimiter with split method, then get it right back using join like:
// Lets say that the value is 10.05.53.324.343
var num1 = document.querySelector('.number1');
num1.innerHTML = num1.innerHTML.split('.').join(','); // Outputs 10,05,53,324,343
You could use the Intl.NumberFormat object instead of replacing characters:
Perhaps you have other numbers on your content that you want to format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
But you can check a working example below that formats a number on US-EN format to pt-BR:
var el = document.querySelector('.number1');
var value = parseFloat(el.textContent);
var newValue = new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2 }).format(value);
el.innerHTML = newValue;
<span class="number1">10.00</span>

extract number using regex

I have a string:
name:demo;morestuff.nbvideo:3;morestuff_here:45
from which I need to extract the nbvideo number. I managed it with 2 regexes, but I'm sure it can be done in just one regex.
Here's what I have now:
// get the nbvideo:XX part
videoPart = sink.tag.match(/nbvideo:([0-9]+)/gi);
// get the number from the video part
videoCount = videoPart[0].match(/([0-9]+)/gi)[0];
How can I extract the number behind 'nbvideo:' with one single regex?
Remove g from the modifiers and access the first capture group value like this:
var sink_tag = "name:demo;morestuff.nbvideo:3;morestuff_here:45";
var m = sink_tag.match(/nbvideo:([0-9]+)/i);
if (m) {
videoPart = m[1];
document.body.innerHTML = videoPart; // demo
}
The thing is that string#match does not keep captures if a global modifier is used with a regex, and it seems you just have one nbvideo:<NUMBER> in the input. So, removing /g seems to be enough. Else, use RegExp#exec() in a loop.

how to simplfy this code

What would be a good way to do this. I have a string with lots of "<" and > and I want to replace them with < and >. So i wrote this:
var str = </text><word34212>
var p = str.replace('\&lt\;','\<');
var m = p.replace('\&gt\;','\>');
but that's just doing the first instance of each - and subsequent instances of </> are not replaced. I considered first counting the instances of the < and then looping and replacing one instance of the code on every iteration...and then doing the same for the > but obviously this is quite long-winded.
Can anyone suggest a neater way to do this?
To replace multiple occurances you use a regular expression, so that you can specify the global (g) flag:
var m = str.replace(/</g,'<').replace(/>/g,'>');
Taken from: http://www.bradino.com/javascript/string-replace/
The JavaScript function for String
Replace replaces the first occurrence
in the string. The function is similar
to the php function str_replace and
takes two simple parameters. The first
parameter is the pattern to find and
the second parameter is the string to
replace the pattern with when found.
The javascript function does not
Replace All...
To ReplaceAll you have to do it a
little differently. To replace all
occurrences in the string, use the g
modifier like this:
str = str.replace(/find/g,”replace”)
You need to use the global modifier:
var p = str.replace(/\&lt\;/g,'\<');
You need to use de /g modifier in your regex and it'll work. Check this page for an example : http://www.w3schools.com/jsref/jsref_replace.asp
I thing a associative array [regex -> replacement] and one iteration would do it

Categories

Resources