Question

I have a string, part of which looks like this:

"..devices=233.423.423.553&..."

and I'd like to replace the values of "devices=" with different values like "111.111" so it would appear like:

"..devices=111.111&..."

I think I can do that with some sort of expressions since I need to do that inline.Any trick would be appreciated..

Was it helpful?

Solution 2

I'm a relative noob, so forgive me if this is completely inefficient, but how about:

var myStr="..devices=233.423.423.553&..."
var something=myStr.substring((myStr.indexOf("=")+1),(myStr.indexOf("&")));
myStr.replace(something,"111.111.111");

Using regular expressions looks cooler, though.

OTHER TIPS

Sure.. Just replace with the string you want to replace with:

var str = '..devices=233.423.423.553&...';
str = str.replace(/devices=[0-9.]+/g, 'devices=111.111');

console.log(str); //..devices=111.111&... 

Autopsy:

  • devices= the literal string devices=
  • [0-9.]+ the digits 0 to 9 or the literal character . matched 1 to infinity times
  • /g means "global". Will replace any occurence rather than just the first one

Regular expression visualization

Just try with:

 "..devices=233.423.423.553&...".replace(/(devices)=(?:\d+(\.\d+)*)/, '$1=111.111')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top